Call, bind and apply explicitly attach this into the object or function.
call attaches this into function and executes the function immediately:1
2
3
4
5
6
7var person = {
name: "Danny"
speaking: function(thing){
console.log(this.name + "says Hi!" + thing)
}
}
person.speaking.call(person, "Irene") // "Danny says Hi! Irene"
bind attaches this into function and it needs to be invoked separately1
2
3
4
5
6
7
8var person = {
name: "Danny"
speaking: function(thing){
console.log(this.name + "says Hi!" + thing)
}
}
var hello = person.speaking.bind(person)
hello("Irene"); // "Danny says Hi! Irene"
apply is similar to call except that it takes an array-like object instead of listing the arguments1
2
3
4
5
6
7
8var obj = {num:2};
var addToThis = function(a,b,c){
return this.num + a + b + c;
}
console.log(addToThis.call(obj, 1, 2, 3)); // 8
var arr = [1,2,3]
console.log(addToThis.apply(obj, arr)); // 8