我想从类内部调用其他类方法,但是当某些方法调用方法时,由于现在this是调用方法,并且无法使用其他类方法或获取数据成员,因此无法访问this

例如:

class someclass{

    _this = this;

    foo(){
        this.bar();
    }

    bar(){
        this.baz();  // this is foo not someclass
        _this.baz(); // _this is not defined
    }

    baz(){

    }
}

那么,我如何始终可以访问实际的类以调用其方法并使用其方法中的数据成员呢?

编辑:在我的实际代码中,我还有另一个对象,该对象通过事件调用foo,因此this是输入foo而不是someclass时的该对象。

最佳答案

Javascript中的类方法默认情况下不受约束。含义this的值取决于如何调用它们,而不是如何调用
被定义。

要在ES6中绑定(维护this):

class SomeClass {
    constructor() {
       // This binding maintains the value of this
       // inside these methods during future calls.
       this.foo = this.foo.bind(this)
       this.bar = this.bar.bind(this)
       this.baz = this.baz.bind(this)
    }

    foo() {
        this.bar();
        console.log('from foo')
    }

    bar() {
        this.baz();  // This is foo not SomeClass
        console.log('from bar')
    }

    baz() {

    }
}
// If you are using Babel you can use arrow function/methods
class SomeClass {

    foo = () => {
      this.bar();
      console.log('from foo')
    }

    bar = () => {
      this.baz();  // This is foo not SomeClass
      console.log('from bar')
    }

    baz() {

    }
}

const s = new SomeClass()
s.foo()

控制台输出:
"from bar"
"from foo"

09-20 23:00