shinzou
shinzou

Reputation: 6192

Getting "this" of an ES6 class to call methods and get data members

I want to call other class methods from inside a class but when some method call a method, I lose access to this because now this is the calling method and can't other class methods or get data members.

For example:

class someclass{

    _this = this;

    foo(){
        this.bar();
    }

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

    baz(){

    }
}

So how can I always have access to the actual class to be able to call its methods and use its data members from its methods?

EDIT: in my actual code, I have another object that calls foo with an event, so this is that object when entering foo and not someclass.

Upvotes: 5

Views: 5417

Answers (2)

Ahmed Eid
Ahmed Eid

Reputation: 4804

Class methods in Javascript are not bound by default. Meaning this value depends on how they were called, not how they were defined.

To bind (maintain this) in 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 output:

"from bar"
"from foo"

Upvotes: 7

Amr Aly
Amr Aly

Reputation: 3905

        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

Upvotes: 0

Related Questions