In a JavaScript class, I have a function that calls a callback using a constructor's own variable. To not copy the entire class I will write an example:
class Foo {
constructor(bar) {
this.bar = bar;
}
async_print() {
setTimeout( function() {
console.log(this.bar);
}, 1000);
}
}
This gives an error because this
refers to the context of the function and not to the Foo
object, so I tend to solve it by using a variable self
that refers to this
when still It's what I want it to be. For example:
class Foo {
constructor(bar) {
this.bar = bar;
}
async_print() {
const self = this;
setTimeout( function() {
console.log(self.bar);
}, 1000);
}
}
However, I am left with the feeling that the use of a variable self
is a fix that should be avoided. I know there is a solution through the binding, but I have also seen that in ES6 you can call an arrow function.
In the Mozilla developer documentation, it is explained by using this example :
function Persona(){
this.edad = 0;
setInterval(() => {
this.edad++; // |this| apunta al objeto Persona
}, 1000);
}
However, that only works for me if I have to use a function or act with a variable, but it does not help me to obtain it directly. That is, I can not return such value to use it for example in console.log
. We are talking about a value that I use many times, so I do not see viable doing an arrow function every time I need to interact with it.
What am I missing? How can I get that value within the callback?
Thank you very much