Reputation: 6481
Consider the following code:
function Plant () {
this.country = "Mexico";
this.color= "yellow";
}
Plant.prototype.showDetails = function() {
console.log("I am from " + this.country + " and my color is " + this.color);
}
var banana = new Plant();
banana.showDetails(); //this outputs "I am from Mexico and my color is Yellow".
Now my question is, how does showDetails get access to country and color properties of Plant function even though it is outside the function? (Javascript has scopes as per functions, lexical scoping).
I did some introspection and found that when banana.showDetails is invoked, 'this' refers to Plant object and not banana object. Why is this so? In JS, 'this' refers to the object that calls the function, which in this case is the banana object.
Upvotes: 0
Views: 92
Reputation: 622
You created banana object as a new Plant object, since you're not defining it's own properties it uses properties defined in Plant.
If you define properties on banana, like this:
banana.country = "Serbia";
banana.color = "red";
then you'll get values from banana properties. So basically this refers to banana but banana uses properties inherited from Plant.
Upvotes: 0
Reputation: 85827
country
and color
are not properties of the Plant
function; they are properties of whatever object was bound to this
when Plant
was called.
Doing new Plant()
creates a new object, then calls Plant
with this
bound to the new object.
(In some sense, every JavaScript function has two parameters, this
and arguments
, which are set by every function call (disclaimer: does not apply to "fat arrow" style functions).)
The following code is morally equivalent to your code, just without using constructors/methods:
function Plant(x) {
x.country = "Mexico";
x.color = "yellow";
return x;
}
function showDetails(x) {
console.log("I am from " + x.country + " and my color is " + x.color);
}
var banana = Plant({});
showDetails(banana);
Upvotes: 1