如果从嵌套对象的方法中使用,如何使 "this" 关键字引用当前实例?

How to make "this" keyword refer to current instance, if used from a nested object's method?

在 JavaScript 中,如果我将一个函数附加到对象的原型,在该函数中,this 指的是该对象的当前实例。例如:

function RageFest(inquiry) {
    this.inquiry = inquiry;
}

RageFest.prototype.myFunction0 = function () {
    console.log(this.inquiry);
};

new RageFest("you mad, bro?").myFunction0(); // prints "you mad, bro?"

运行 这在 Node 中打印 you mad, bro? 到终端,正如预期的那样。

现在,这就是我 运行 遇到麻烦的地方:假设我想引入第二层组织(可能是因为 RageFest 附有很多方法,我想组织它们).

RageFest.prototype.myObject = {
    myFunction1: function () { console.log(this.inquiry); },
    myFunction2: function () { console.log(this.inquiry); }.bind(this),
    myFunction3: function () { console.log(this.inquiry); }.bind(RageFest)
};

var ragefest = new RageFest("you mad, bro?");

ragefest.myObject.myFunction1(); // undefined
ragefest.myObject.myFunction2(); // undefined
ragefest.myObject.myFunction3(); // undefined

None 这些作品!如果我让 myObject 的三个函数记录 this(而不是 this.inquiry),它表明:

但是,绑定 实例 (而不是构造函数)有效:

RageFest.prototype.myObject.myFunction4 = function () {
    console.log(this.inquiry);
}.bind(ragefest);

ragefest.myObject.myFunction4(); // prints "you mad, bro?"

这会根据需要打印出 you mad, bro?,但感觉就像一个糟糕的 hack。它还要求我事先创建一个 RageFest 的实例,这很烦人。

所以,我的问题是,有没有一种方法可以实现我想要的效果——嵌套对象中的函数可以使用 this 关键字访问当前实例——而无需求助于这种 hackery ?

创建 getter 而不是创建嵌套对象会有所帮助,它将在构造函数中调用并分配给对象 属性.

function RageFest(inquiry) {
    this.inquiry = inquiry;
    this.myObject = this.getMyObject();
}

RageFest.prototype.myFunction0 = function () {
    console.log(this.inquiry);
};

RageFest.prototype.getMyObject = function(){
    var that = this;
    return {
      myFunction1: function () { console.log(that.inquiry); },
      myFunction2: function () { console.log(that.inquiry); } 
    }
};

var ragefest = new RageFest("you mad, bro?");
ragefest.myObject.myFunction1();
ragefest.myObject.myFunction2();