简体   繁体   English

原型如何通过“ this”访问构造函数的成员?

[英]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? 现在我的问题是,即使showDetails不在功能的外部,它如何访问Plant功能的国家和颜色属性? (Javascript has scopes as per functions, lexical scoping). (Javascript具有按函数的作用域,词法作用域)。

I did some introspection and found that when banana.showDetails is invoked, 'this' refers to Plant object and not banana object. 我进行了一些自省,发现当调用banana.showDetails时,“ this”是指Plant对象而不是香蕉对象。 Why is this so? 为什么会这样呢? In JS, 'this' refers to the object that calls the function, which in this case is the banana object. 在JS中,“ this”是指调用函数的对象,在这种情况下为香蕉对象。

country and color are not properties of the Plant function; countrycolor不是Plant功能的属性; they are properties of whatever object was bound to this when Plant was called. 它们是调用Plant时与this对象绑定的任何对象的属性。

Doing new Plant() creates a new object, then calls Plant with this bound to the new object. new Plant()创建一个新的对象,然后调用Plantthis绑定到新的对象。

(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).) (从某种意义上讲,每个JavaScript函数都有两个参数thisarguments ,这是由每个函数调用设置的(免责声明:不适用于“胖箭头”样式的函数)。)

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. 您将香蕉对象创建为新的Plant对象,因为您没有定义它自己的属性,因此使用Plant中定义的属性。 If you define properties on banana, like this: banana.country = "Serbia"; banana.color = "red"; 如果您在香蕉上定义属性,如下所示: 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. 因此,基本上,这是指香蕉,但是香蕉使用从Plant继承的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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