[英]How does prototype get access to constructor function's members through “this”?
考虑以下代码:
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".
现在我的问题是,即使showDetails不在功能的外部,它如何访问Plant功能的国家和颜色属性? (Javascript具有按函数的作用域,词法作用域)。
我进行了一些自省,发现当调用banana.showDetails时,“ this”是指Plant对象而不是香蕉对象。 为什么会这样呢? 在JS中,“ this”是指调用函数的对象,在这种情况下为香蕉对象。
country
和color
不是Plant
功能的属性; 它们是调用Plant
时与this
对象绑定的任何对象的属性。
做new Plant()
创建一个新的对象,然后调用Plant
与this
绑定到新的对象。
(从某种意义上讲,每个JavaScript函数都有两个参数this
和arguments
,这是由每个函数调用设置的(免责声明:不适用于“胖箭头”样式的函数)。)
以下代码在道德上与您的代码等效,只是不使用构造函数/方法:
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);
您将香蕉对象创建为新的Plant对象,因为您没有定义它自己的属性,因此使用Plant中定义的属性。 如果您在香蕉上定义属性,如下所示: banana.country = "Serbia"; banana.color = "red";
banana.country = "Serbia"; banana.color = "red";
那么您将从香蕉属性中获得价值。 因此,基本上,这是指香蕉,但是香蕉使用从Plant继承的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.