Learn call, apply and bind in javascript | by Bytecode pandit
Hi! Today I'll talk about the important topic call, apply, and bind. These javascript methods allow us to change the value of this for a given function. And I will try to make these concepts as simple as that with appropriate examples.
Function.prototype.call()
The method invokes the function and allows us to one by one using commas.
var testArgument = {firstName: "John", lastName: "Smith", age: 24, profession: "Developer"};
function testFunction(text) {
console.log("value of this", this);
console.log("value of text", text);
}
testFunction.call(testArgument, "hello");
// output
/*
value of this {firstName: "John",
lastName: "Smith", age: 24, profession: "Developer"}
value of text hello
*/
you call also pass array or string
var testArgument = "String"
function testFunction(text) {
console.log("value of this", this);
console.log("value of text", text);
}
testFunction.call(testArgument, "hello");
// output
/*
value of this String {"Hello"}
value of text hello
*/
Function.prototype.apply()
This method is almost similar to call, there is only one difference that you have to pass the argument in the array.
var testArgument = {country: "India", city: "Mumbai"};
function testFunction(text, text2, text3) {
console.log("value of this", this);
console.log("value of firstname", text);
console.log("value of middlename", text2);
console.log("value of lastname", text3);
}
testFunction.apply(testArgument, ["Rohit", "Kumar", "sinha"]);
// output
/*
value of this {country: "India", city: "Mumbai"}
value of firstname Rohit
value of middletname Kumar
value of lastname sinha
*/
Function.prototype.bind()
The bind method returns you a new function with the new value of this. And then you can call it anytime with the arguments.
var testArgument = {country: "India", city: "Mumbai"};
function testFunction(text, text2, text3) {
console.log("value of this", this);
console.log("value of firstname", text);
console.log("value of middlename", text2);
console.log("value of lastname", text3);
}
var newTestFunction = testFunction.bind(testArgument);
newTestFunction("Rohit", "Kumar", "Sinha");
// output
/*
value of this {country: "India", city: "Mumbai"}
value of firstname Rohit
value of middletname Kumar
value of lastname Sinha
*/
Use it when you want that function to later be called with a certain context like events.
That's all folks
I hope now you guys have understood call apply, and bind in a very simple term. And thanks for reading this article.
Nice info!
ReplyDeleteReally informative and easy to understand , thanks prakash
ReplyDelete