5 ms·
The main benefit of arrow function generators would be the inherited parent-scope this-binding they'd get
by inbx0 4y ago
The main benefit of arrow function generators would be the inherited parent-scope this-binding they'd get
- javajosh 4y agoYeesh! I personally stay away from "this" as much as I can, in part because of this effect. I can't imagine using the arrow function's odd "this" behavior intentionally! Plus, I like pure functions a lot so I'd rather just pass in any state through a parameter, which is less error-prone too.
- int_19h 4y agoWhy is the arrow-function "this" behavior odd? It captures it from the outer scope, just like it does with all other local variables. This is exactly how it works in pretty much every other language out there. It's the old-style "function" behavior that always determines "this" at the point of the call that's odd, if anything.
- javajosh 4y ago>Why is the arrow-function "this" behavior odd? Because it behaves very differently from ordinary function "this" behavior. Your statement about "this" being defined at the function call site is just...wrong.
- int_19h 4y agoIt's literally how it works for arrow-less functions, though - "this" is bound to the receiver at call site: foo = function() { console.log(this.n); }; o1 = { foo, n: 1 }; o2 = { foo, n: 2 }; o1.foo(); // 1 o2.foo(); // 2 I can't think of any other language that does it this way. Arrow-functions, OTOH, behave as lambdas normally do: foo = () => { console.log(this.n); }; o1 = { foo, n: 1 }; o2 = { foo, n: 2 }; o1.foo(); // undefined o2.foo(); // undefined
- javajosh 4y agoNeither of these code snippets demonstrate binding 'this' at the call site. In any event, I strongly suggest avoiding 'this' as much as humanly possible in javascript because a) it's wonky and b) you never need it.
- inbx0 4y agoIn 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.
- int_19h 4y agoWhere do you think the binding happens in my example, then?
- inbx0 4y agoIn line 3, where it's called })(); With this way of invoking, `this` will be `undefined` in "strict mode" (i.e. if the file or parent function has 'use strict' or if we are in an ES module), and Window in "sloppy mode".