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
.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With