26 ms·
I haven't touched JavaScript in years, so I'm curious about one detail: why does the second snippet need you to alias "this" to "my" and the first doesn't? If i
by CodeMage 11y ago
I haven't touched JavaScript in years, so I'm curious about one detail: why does the second snippet need you to alias "this" to "my" and the first doesn't? If it wasn't for that, it would look like mere syntactic sugar for lambdas, but this difference makes me think there's something more to it.
- lobster_johnson 11y agoFunction calls bind "this" to the caller. So if you do: foo.bar() then inside bar(), "this" is foo. Whereas if you do: quux(function() { console.log(this); }) ...the "this" will point to whatever quux's "this" is, and it could be anything, depending on what quux() is doing. You can't depend on "this" being correct here. Hence people have for years used bind(): quux(function() { console.log(this); }.bind(this)); But this is neither nice to read (or write), nor is it performant. Many libraries, such as Underscore, also allow you to pass in a context variable: quux(function() { console.log(this); }, this); This requires that quux() passes the context as the "this" argument to the function. The lambda (arrow) syntax fixes all of this [pun] by preserving "this" as a lexically scoped reference: quux(() => console.log(this));
- striking 11y agoIt actually is required, because `this` is mangled whenever you create a function. If I added .bind(this) to the function, it would also work, but I alias the object instead. Yes, it's confusing, but the fact that there's a difference is even more confusing.
- mohaine 11y agoIt is a feature of the new syntax to bind the current context (what "this" points to) to the created function. http://tc39wiki.calculist.org/es6/arrow-functions/ http://tc39wiki.calculist.org/es6/arrow-functions/
- notNow 11y ago"this" inside the setInterval in the 2nd example points to the global object in the browser case it's the window. So, he had to cache/alias the value prior to execution to avoid the confusion.