2 ms·
That should work in the provided example, but in general `fn(cb)` is different: you lose the implied `this` binding unless you do `cb.bind(something)` beforehan
by hoten 6y ago
That should work in the provided example, but in general `fn(cb)` is different: you lose the implied `this` binding unless you do `cb.bind(something)` beforehand.
There's also some unexpected trouble due to potential extra parameters. Consider the output of
['1', '2', '3'].map(parseInt)
gives:
[1, NaN, NaN]
So yea, fn(() => cb()) is the same as fn(() => {return cb()}) – just syntactic sugar when the anonymous function has just one statement. but fn(cb) is semantically different.
- jfengel 6y agoI consider myself a pretty advanced JS developer, and I still don't understand how "this" works in JS. I avoid using it whenever I can.
- hoten 6y agoYea, 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.