Hello Everyone,
I came across a snippet where code have .call() method.
Thought its been a while since I went through their understanding, via this article I am explaining with examples what call, bind and apply does in javascript.
Please read comments for understanding.
Hope it helps.
var obj = {
name: "Raja",
sayHello: function(args) {
console.log(`Hello ${this.name}, How are you doing `);
},
};
// call : Changing the context::this scope to the argument we are passing.
// normal
obj.sayHello() // Hello Raja, How are you doing ?
obj.sayHello.call({name : "Rajasekhar"}); // Hello Rajasekhar, How are you doing ?
var obj = {
name: "Raja",
sayHello: function(args) {
console.log(`Hello ${this.name}, How are you doing ? ${args}`);
},
};
// apply: same as call, we can also pass arguments as 2nd argument
obj.sayHello.apply({ name: "Rajasekhar" }, ["Testing"]); // Hello Rajasekhar, How are you doing ? Testing
// bind: Change function definition to a different context
// you can change the definition once
var obj = {
name: "Raja",
sayHello: function(args) {
console.log(`Hello ${this.name}, How are you doing ? ${args}`);
},
};
var contxt = {"name" : "ApplyContext:)"};
var newHello = obj.sayHello.bind(contxt);
newHello("Good Day!!!"); // Hello ApplyContext:), How are you doing ? Good Day!!!
0 comments:
Post a Comment