Regardless of the performance, for some use cases, arrow function cannot represent the same logic. For example, when you use Promises you can have something like this (source for this example):
function CommentController(articles) {
this.comments = [];
articles.getList()
.then(function (articles) {
return Promise.all(articles.map(function (article) {
return article.comments.getList();
}));
})
.then(function (commentLists) {
return commentLists.reduce(function (a, b) {
return a.concat(b);
});
})
.then(function (comments) {
this.comments = comments;
}.bind(this));
}
Note the difference if the last bind(this)
were removed. There's no simple way to use arrow function notation to change this without modifying the code a lot. I personally prefer to use closure with variable name other than this
for a code like this, though.
In addition, bind()
can be used for partial application which may be easier to read for people with functional programming background.
On the other hand, if a.someMethod
is modified later, the version that used bind()
will not see the change because it took the reference to the function during the binding. The variant with lambda function will see current value of a.someMethod
when y()
is called.
Additional example about needing .bind(this)
:
let f =
{
x: "bind data",
test: function()
{
console.log("1. this=", this);
setTimeout(function() {
console.log("2. this=", this);
}, 0);
setTimeout(function() {
console.log("3. this=", this);
}.bind(this), 0);
}
}
f.test();