Reputation: 67
I'm trying to understand one thing about constructors. Namely I don't understand how function object's properties, aka constructor's properties can't be accessed using Foo.prototype.property, example:
//let's create new function object with predefined properties
function Foo() {
this.name = "Mike";
this.returnName = function() {
return 'This persons name is ' + this.name + '.';
};
};
//now let's create new object using constructor and prototypal inheritance
var mike = new Foo();
mike.returnName(); //returns "This persons name is Mike."
I understand that mike inherits properties from Foo's prototype. So these properties must be present inside of the prototype. new object points toward the prototype with internal prototype link using __ proto __. I get that. Thing that I can't get around is how this doesn't work:
Foo.prototype.returnName();
Constructor has .prototype link with prototype property and vice versa prototype has .constructor link with the Foo.
I know that calling the Foo(); function first then calling for window.returnName(); would return the sentence, since this context is set to window.
Is this because when I call the method using prototype it assigns it to the window? Is there any way I could access/call this constructor's property?
Upvotes: 1
Views: 48
Reputation: 9929
You are not specifying returnName on the prototype of Foo. If you would do it like this:
function Foo(){
this.name = "Mike";
}
Foo.prototype.returnName = function(){
return 'This persons name is ' + this.name + '.';
};
var mike = new Foo();
mike.returnName();
Things would be different.
Upvotes: 1
Reputation: 57729
The function returnName
is not assigned to the prototype of Foo
. Instead it's assigned to every instance of Foo
, just like the name
is "Mike"
.
Whenever you call new Foo()
a new context is created, this is the this
context of that instance.
If you call Foo()
directly (without new
) this
is the global object (window
).
Upvotes: 0