【问题标题】:js: method can't access propertyjs:方法无法访问属性
【发布时间】:2016-11-18 22:17:27
【问题描述】:

在 JavaScript 中让我感到困惑的是:在下面的代码中,我有一个包含一个属性的对象构造函数。在它下面,我添加了一些原型方法。方法 'method1' 能够很好地访问 'this.property',它返回值 30。方法 'combine' 只是调用了 'method1',但它返回 NaN。似乎“this.property”对第一次调用是公开的,但不是第二次调用。为什么会有这种奇怪的行为?

var ObjBuilder = function()
{
  this.property = 3;
};

ObjBuilder.prototype = function()
{
  var method1 = function()
  {
    return this.property * 10;
  }
  var combine = function()
  {
    return method1() + 2;
  }
  return {method1: method1,
          combine: combine};
}();

// instantiate an object and call its methods
var obj = new ObjBuilder();
console.log(obj.method1());//prints 30
console.log(obj.combine());//prints NaN. WHY???

【问题讨论】:

  • 如果你在method1 中记录this 然后在combine 中调用它,你会看到问题
  • @t.niese It doesn't seem like it - window。您必须将其称为 this.method1() 以提供 this 上下文。

标签: javascript oop scope prototype


【解决方案1】:

我认为你的问题是combine 只是调用了method1 函数(例如,不是this.method1),所以this.property * 10 中的thismethod1 的调用中没有像你期望的那样绑定并且可能绑定到全局对象。

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 2018-02-16
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 2013-11-23
    • 2018-03-02
    • 1970-01-01
    相关资源
    最近更新 更多