Le 25/03/2022 à 05:57, luserdroog a écrit :
everybody knows that arrow functions inside methods forget their 'this'.
Does everybody else know how to work around that? Does `bind()` do
something helpful?
Don't know what you mean...
class Test {
constructor(name) {
this.name = name;
}
getName(delay) {
setTimeout(
() => {
console.log(this.name);
}, delay);
}
}
const t1 = new Test("test 1");
const t2 = new Test("test 2");
t1.getName(500);
t2.getName(100);
test 2
test 1
anonymous arrow function inherits this from the function where it is
defined (the getName method) whose this is the test object.
of course
const f = t1.getName;
f(100);
D:\xxxxxxxxxxxxxxxxxxxxxxx\test.js:10
console.log(this.name);
TypeError: Cannot read properties of undefined (reading 'name')
the call to method getName via f(100) make this to be undefined so is
this for arrow function
and
const f = t1.getName.bind(t1);
f(100);
test 1
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)