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

时间:2017-03-26 08:17:34

标签: 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(){

    }
}

那么如何才能始终访问实际的类以便能够调用其方法并从其方法中使用其数据成员呢?

编辑:在我的实际代码中,我有另一个使用事件调用foo的对象,因此在输入this而不是foo时,someclass就是该对象。< / p>

2 个答案:

答案 0 :(得分:5)

默认情况下,

javascript中的类方法不受约束。含义 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(){ } }
// 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()
console

"from bar"

"from foo "

lib/my_engine/engine.rb

答案 1 :(得分:0)

&#13;
&#13;
        class someClass2 {
           bar() {
            console.log('bar from someClass2')
          }
    
        }
    
       class someClass {
          
           constructor() {
             //instantiate an object of someClass2 to access all itsmethod
             this.obj2 = new someClass2()
             
           }
    
           foo () {
            console.log('foo from someClass')
          }
          barFromObj2(){
            return this.obj2.bar()
          }
      }
    
        var obj = new someClass();
    
        obj.foo(); // return foo from someClass
    
        // access the bar method from the someClass2
        obj.barFromObj2(); // return bar from someClass2
&#13;
&#13;
&#13;