类 - 'this' 对比 'self'

Classes - 'this' vs 'self'

我正在使用新的 ES6 Classes 并且很难理解为什么我可以引用 this 变量是其中一种方法。

//CLASS

class Form{ 
    constructor(){
        var self = this;
    }   

    assemble(){
        log(self);
    }
}

//呼叫

var form = new Form();
form.assemble();

//RETURN

window object (not the reference to the class object)

this 不是变量。它更像是函数的隐藏参数。

您无法在您的示例中访问 self,因为它是构造函数中的局部变量,因此它对您的 assemble 方法不可用。

您的示例根本不需要 self,只需使用 this:

class Form {
    assemble(){
        log(this);             // ***
    }
}
var form = new Form();
form.assemble();

如果您将 form.assemble 传递给不能保证用正确的 this 调用它的对象,您可以将 assemble 定义为实例函数成员,方法是定义它在构造函数中;然后它将关闭 self。但是在 ES2015 及更高版本中你不需要 self;只需使用箭头函数,它关闭 this:

class Form {
    constructor(){
        var self = this;
        this.assemble = () => {
            log(this);
        };
    }   
}
var form = new Form();
form.assemble();          // Works
var f = form.assemble;
f();                      // Also works

但很可能您不需要这样做。