Why does Function.x work after Function.prototype.x is declared?

As I understand it, the prototype property of a function is how you add methods / properties to all objects created from that function.

So when I try something like this

function Person(){}
Person.prototype.saySomething = function(){ alert( "hi there" ); }



I am getting the error "Person.saySomething is not a function" which makes sense since Im not acting as an instance of a Person object.

But why does the code below work?

Function.prototype.sayHi = function(){ alert( "hi!" );}




source to share

1 answer

First you need to create an instance Person


new Person().saySomeThing();


Prototype methods / properties are only inherited when the constructor is instantiated using the keyword new



works because the constructor Function

has a function as well .



All Articles