2 ms·
In the first example, when you look at the first line foo = function() { console.log(this.n); }; You cannot possibly know what "this" refers to when the fun
by inbx0 4y ago
In the first example, when you look at the first line
foo = function() { console.log(this.n); };
You cannot possibly know what "this" refers to when the function is eventually called. Is it some object? Is it the surrounding class or function? Is it window? Is it undefined? Is it the function itself?
There's no way to know, because it hasn't been decided yet. Deciding what `this` refers to in the "normal"/non-arrow functions is up to the caller.
o1.foo();
Here, `this` will be o1.
o2.foo();
here, `this` will be o2.
o1.foo.call("hello")
here, `this` will be `new String("hello")`.
That's what the parent commenter meant by "binding this at the call site".
Classes are still very common out there, despite the popularity of e.g. React function components etc, and `this` is pretty essential with classes.