3 ms·
Yea, you can avoid it without losing much at all. Most common place IME you end up needing to use it are when assigning functions on a class as event listeners
by hoten 6y ago
Yea, you can avoid it without losing much at all.
Most common place IME you end up needing to use it are when assigning functions on a class as event listeners: if you want to be able to remove them, you need to use the same value in `addEventListener` as `removeEventListener`; and if the function uses other properties of the class, you must use `.bind(this)` to correctly set `this`.
It may help to think of it like this. This code
object.someFunction(a, b);
is syntactic sugar for
someFunction.call(object, a, b)
So with most usages of functions, the `this` is implicitly defined. The trouble comes when you start passing around references to functions.
const fn = object.someFunction;
fn(a, b); // throw `this is undefined` error if function accesses this
Here, `this` was never defined. So you need to do one of:
const fn = object.someFunction.bind(object);
fn(a ,b);
// OR
fn.call(object, a, b);
The last thing you need to know is the difference between arrow functions and classic functions. Arrow functions _never_ have a `this` binding of its own. It doesn't make a scope. If the scope it was defined in happened to already define `this`, it would use that. Classic functions (`function blah() {}` or `const fn = function() {}`) do make a new scope, so they have a `this` binding, so if you wanted to access `this` of the outer scope you'd have to assign it to another variable beforehand
class A {
a = 1;
fn() {
const thisRef = this;
return function () { return thisRef.a }
}
}
With arrow functions, it's easier:
class A {
a = 1;
fn() {
return () => { return this.a }
}
}
I think this is all you'd ever need to know.