【问题标题】:How does prototype get access to constructor function's members through "this"?原型如何通过“this”访问构造函数的成员?
【发布时间】: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


【解决方案1】:

countrycolor 不是 Plant 函数的属性;它们是在调用 Plant 时绑定到 this 的任何对象的属性。

执行new Plant() 创建一个新对象,然后调用Plant 并将this 绑定到新对象。

(从某种意义上说,每个 JavaScript 函数都有两个参数,thisarguments,它们由每个函数调用设置(免责声明:不适用于“胖箭头”样式的函数)。)

以下代码在道德上等同于您的代码,只是不使用构造函数/方法:

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

【讨论】:

  • 你的意思是说当 javascript 解释器在本地对象?
  • @dk49 对象不会传递给其他对象。事物被传递给函数。 (从对象获取属性遵循原型链。)我不确定你在问什么。
【解决方案2】:

您将香蕉对象创建为新的 Plant 对象,因为您没有定义它自己的属性,它使用 Plant 中定义的属性。 如果您在香蕉上定义属性,如下所示: banana.country = "Serbia"; banana.color = "red"; 然后您将从香蕉属性中获取值。所以基本上这指的是香蕉,但香蕉使用从植物继承的属性。

【讨论】:

    猜你喜欢
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    相关资源
    最近更新 更多