Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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));


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: