【发布时间】:2016-06-05 21:01:32
【问题描述】:
考虑以下代码:
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对象而不是banana对象。为什么会这样?在 JS 中,'this' 指的是调用函数的对象,在本例中是香蕉对象。
【问题讨论】:
-
因为您正在将 showDetails 添加到 Plant 原型中,就这么简单。
-
"'this' 指的是植物对象而不是香蕉对象。" 这并不完全准确。
this确实指的是banana。 “Plant 对象”可能是指“Plant 的实例”,它是 sn-p 中的香蕉,而不是构造函数本身。 -
.country和.color是属性,而不是词法范围的变量。它实际上只是访问绑定到this的对象的属性 - 当您调用banana.showDetails()时会动态发生 -
How does the “this” keyword work? 的可能重复项 - 该方法是否继承自原型对象并不重要。
-
@Jonathan Lonowski :当我在 showDetails 方法中执行 console.log(this) 时,它会在控制台中输出 Plant {country: "Mexico", color: "yellow"}。这很奇怪,因为 Plant 不是一个对象,而是一个函数。如果 this 指的是香蕉对象,则输出应该是香蕉 {country: "Mexico", color: "yellow"}。
标签: javascript prototype