如何在 JavaScript 类中访问“self”?

Sco*_*ott 0 javascript

注意:我不想重新绑定this关键字。我想this引用调用对象。但是,我希望能够引用定义我的方法的类的实例。如何访问实例?

在 JavaScript 中,this关键字指的是调用对象。所以,当我定义一个类时:

class A {
    x = 5;
    printx() {
        console.log(this.x);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,当我printx直接从 的实例调用该方法时A,我得到 5:

a = new A();
a.printx();
Run Code Online (Sandbox Code Playgroud)

但是当我printx从不同的上下文中调用时,this.x不是a.x,它可能是window.x或其他东西:

b = a.printx;
b(); // TypeError: this is undefined
Run Code Online (Sandbox Code Playgroud)

我想以printx这样的方式定义 Calling bwill console.log(5)self即,我想从 Python获取行为。我如何self在 JavaScript 中引用?

Bro*_*697 5

用于function.prototype.bind在分配时将函数绑定到上下文b

class A {
    x = 5;
    printx() {
        console.log(this.x);
    }
}

let a = new A()
let b = a.printx.bind(a)

b()
Run Code Online (Sandbox Code Playgroud)