The call
, apply
and bind
methods are NOT suitable as arrow functions – as they were designed to allow methods to execute within different scopes – because arrow functions establish this
based on the scope the arrow function is defined within.
For example call
, apply
and bind
work as expected with traditional functions, because we establish the scope for each of the methods:
var obj = {
num: 100
}
window.num = 2020;
var add = function (a, b, c) {
return this.num + a + b + c;
}
var result = add.call(obj, 1, 2, 3)
console.log(result)
const arr = [1, 2, 3]
var result = add.apply(obj, arr)
console.log(result)
var result = add.bind(obj)
console.log(result(1, 2, 3))
With Arrow functions, since our add
function is essentially created on the window
(global) scope, it will assume this
is the window.
var obj = {
num: 100
}
window.num = 2020;
var add = (a, b, c) => this.num + a + b + c;
console.log(add.call(obj, 1, 2, 3))
const arr = [1, 2, 3]
console.log(add.apply(obj, arr))
const bound = add.bind(obj)
console.log(bound(1, 2, 3))
Perhaps the greatest benefit of using Arrow functions is with DOM-level methods (setTimeout
, setInterval
, addEventListener
) that usually required some kind of closure, call, apply or bind to ensure the function executed in the proper scope.
Traditional function example
var obj = {
count : 10,
doSomethingLater : function (){
setTimeout(function(){
this.count++;
console.log(this.count);
}, 300);
}
}
obj.doSomethingLater();
Arrow function example
var obj = {
count : 10,
doSomethingLater : function(){
setTimeout( () => {
this.count++;
console.log(this.count);
}, 300);
}
}
obj.doSomethingLater();