【问题标题】:Access parent prototype scope from inside self-executing anonymous member function从自执行匿名成员函数内部访问父原型范围
【发布时间】:2016-02-02 20:27:24
【问题描述】:

我正在定义一个 Parent 对象,我希望它有一个子成员对象,该对象拥有自己的函数和私有变量。为了封装函数和变量,我在父原型中添加了一个自执行匿名函数。

这是演示问题的代码:

var Parent = function() {
    this.memberVariable = 'hello world';   
}

Parent.prototype.doSomething = function() {
    return this.childObject.doSomething();
};

Parent.prototype.childObject = function() {
    // instead of being Parent, `this` is the Window object. What is the best way to fix this?
    var that = this;
    
    return {
        doSomething: function() {
            // undefined, but should be 'hello world'
            return that.memberVariable;
        }
    }
}();

var parent = new Parent();
console.log(parent.doSomething());

我有一个解决方法是将 Parent 范围传递给子函数,但这看起来很奇怪,而且似乎必须有更好的解决方案:

var Parent = function() {
    this.memberVariable = 'hello world';   
}

Parent.prototype.doSomething = function() {
    // we pass in `this`
    return this.childObject.doSomething(this);
};

Parent.prototype.childObject = function() {
    return {
        doSomething: function(that) {
            return that.memberVariable;
        }
    }
}();

var parent = new Parent();
console.log(parent.doSomething());

有没有更好的方法来做到这一点?

【问题讨论】:

标签: javascript scope anonymous-function


【解决方案1】:

使用callapply

Parent.prototype.doSomething = function() {
    return this.childObject.doSomething.call(this);
};

或者你可以使用bind:

Parent.prototype.childObject = function() {
    return {
        doSomething: (function() {
            // undefined, but should be 'hello world'
            return this.memberVariable;
        }).bind(this)
    }
}();

【讨论】:

  • .call() 也是我尝试过的方法之一,但我也不太喜欢它,因为它必须附加到对childObject 的每次调用中。这是最好的方法吗?
【解决方案2】:

Parent 构造函数中初始化childObject。否则,Parent 的所有实例将共享相同的childObject。这可能不是你想要的。

function Parent() {
  this.childObject = new Child(this); // or something like makeChild(parent), or just an object literal.
}

function Child(parent) {
  this.parent = parent;
}

【讨论】:

  • 我没有想到这一点,因为 Parent 是一个单身人士,所以我没有考虑 childObject 定义的范围。这是一个更清洁的解决方案。谢谢!
猜你喜欢
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 2011-02-13
  • 2013-08-16
相关资源
最近更新 更多