Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

everybody knows that arrow functions inside methods ...

18 views
Skip to first unread message

luserdroog

unread,
Mar 25, 2022, 12:57:28 AM3/25/22
to
everybody knows that arrow functions inside methods forget their 'this'.
Does everybody else know how to work around that? Does `bind()` do
something helpful?

--
lazy amateur

Arno Welzel

unread,
Mar 25, 2022, 4:19:21 AM3/25/22
to
luserdroog:

> everybody knows that arrow functions inside methods forget their 'this'.
> Does everybody else know how to work around that? Does `bind()` do
> something helpful?

<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions>


--
Arno Welzel
https://arnowelzel.de

Elhwen Dico

unread,
Mar 25, 2022, 10:47:31 AM3/25/22
to
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

Michael Haufe (TNO)

unread,
Mar 25, 2022, 12:32:10 PM3/25/22
to
You use a function instead of a lambda. This is by design.

The alternative is to pass 'this' as an explicit argument:

(self, foo) => {...}

JJ

unread,
Mar 26, 2022, 12:29:17 AM3/26/22
to
Arrow function is not a replacement or a "better" version of the normal
function. Both have different purposes.
0 new messages