Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 442
shinzou Avatar asked Mar 09 '23 12:03

shinzou


1 Answers

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"
like image 177
Ahmed Eid Avatar answered Mar 12 '23 04:03

Ahmed Eid