获取ES6类的"this"来调用方法并获取数据成员

shi*_*zou 3 javascript syntax ecmascript-6 es6-class

我想从类中调用其他类方法但是当一些方法调用一个方法时,我失去了访问权限,this因为现在this是调用方法而不能使用其他类方法或获取数据成员.

例如:

class someclass{

    _this = this;

    foo(){
        this.bar();
    }

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

    baz(){

    }
}
Run Code Online (Sandbox Code Playgroud)

那么我怎么能总是访问实际的类来调用它的方法并从其方法中使用它的数据成员呢?

编辑:在我的实际代码中,我有另一个foo使用事件调用的对象,因此this在进入时foo不是someclass.

aei*_*eid 6

默认情况下,javascript中的类方法不受约束.意义 this值取决于它们的调用方式,而不是它们是如何定义的.

this在es6中绑定(维护)

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(){

    }
}
Run Code Online (Sandbox Code Playgroud)
// 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()
Run Code Online (Sandbox Code Playgroud)

console

"from bar"

"from foo "

  • 他们在诸如`setTimeout(obj.foo)`之类的情况下失去了上下文,这里已经解决了大约一千次,而且几乎可以肯定是OP的潜在问题,尽管他没有提到它.今天你需要的只是`setTimeout(()=> obj.foo())`; 如今,`bind`很少是必要或可取的. (2认同)