简体   繁体   中英

How does prototype get access to constructor function's members through “this”?

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.

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);

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"; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM