Re:Trine – A utility library for functional programming in J...
by CodeMage on Thursday June 11, 2015 @11:31AM
(#9700288)
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.
[ Parent
| on HN ]
Re:Trine – A utility library for functional programming in J...
by lobster_johnson on Thursday June 11, 2015 @11:39AM
(#9700335)
Function 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));
Re:Trine – A utility library for functional programming in J...
by mohaine on Thursday June 11, 2015 @11:41AM
(#9700346)
It is a feature of the new syntax to bind the current context (what "this" points to) to the created function.
Re:Trine – A utility library for functional programming in J...
by striking on Thursday June 11, 2015 @11:40AM
(#9700342)
It 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.
Re:Trine – A utility library for functional programming in J...
by notNow on Thursday June 11, 2015 @12:42PM
(#9700750)
"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.