We fibbed. Arrow functions do not work exactly like anonymous functions. For some situations, they are better.
In addition to providing shorter syntax, arrow functions:
work as though you had written function () {}.bind(this)
, making
this work as expected in the body of the arrow function
allow you to omit the curly braces if you only have one statement
return the result of the single statement when curly braces are omitted
For example, here is CoffeeRun’s CheckList.prototype.addClickHandler method:
CheckList.prototype.addClickHandler = function(fn) { this.$element.on('click', 'input', function (event) { var email = event.target.value; fn(email) .then( function () { this.removeRow(email); }.bind(this)); }.bind(this)); };
Replacing the anonymous functions with arrow functions makes this code a bit clearer:
CheckList.prototype.addClickHandler = (fn) => { this.$element.on('click', 'input', (event) => { let email = event.target.value; fn(email) .then(() => this.removeRow(email)); }); };
The work that addClickHandler is doing
is more apparent without the extra noise of function
and
.bind(this)
.
3.145.96.86