π‘ In JavaScript, call
, apply
and bind
are three methods that are used to manipulate the βthisβ context in a particular function.
First let me create a simple object to explain this:
var person = {
name : "john",
hello: function(thing){
console.log(this.name+ " says hello "+ thing);
}
}
person.hello("world"); //john says hello world
Call, apply and bind allow us to explicitly set the execution context for the this keyword
call
It is used to invoke a function with specified this value and individual arguments. The syntax is:
functionName.call(thisArg, arg1, arg2, ...);
var person = {
name : "john",
hello: function(thing){
console.log(this.name+ " says hello "+ thing);
},
};
var alterEgo = {
name: "Rose"
};
person.hello.call(alterEgo, "world"); //Rose says hello world
apply
It works same as Call method, but here we take array of all our parameters.
for example:
var person = {
name : "john",
hello: function(thing){
console.log(this.name+ " says hello "+ thing);
},
};
var alterEgo = {
name: "Rose"
};
person.hello.call(alterEgo, ["world"]); //Rose says hello world
bind
It works the same as call , but instead of executing the function, it returns a new function that can be executed later. The syntax is:
var newFunction = functionName.bind(thisArg, arg1, arg2, ...);
var person = {
name : "john",
hello: function(thing){
console.log(this.name+ " says hello "+ thing);
},
};
var alterEgo = {
name: "Rose"
};
var helloRose = person.hello.bind(alterEgo, "world");
helloRose(); //Rose says hello world
Top comments (0)