"Say, you created a function. If you can stitch this function to an object, the function then can access that object that it's been stitched to. call, apply, and bind help you do that"
Explained in terms of a straw:
"Say, you have a straw. You haven't yet dipped it in any drink, so what is the drink that's flowing in the straw? Nothing.
But if you dip the straw in juice and start drinking, what is the drink that is running through the straw? Whatever juice you dipped your straw in.
Say, you added some essence to the juice, you gonna suck them too.
So...
Straw.call(juice) ...this is how you attach your function to an object.
Straw.call(juice, essence) ...this is how you attach your function to an object and pass parameters too"
A simple example to explain how a call method works:
var sayHi = function(){
console.log("Hi " + this.name);
}
sayHi(); //returns crazy results as it gets confused with "this"
var person = {"name":"Ramesh"};
sayHi.call(person); // returns Hi Ramesh because person object becomes "this" inside sayHi function.
sayHi.apply(person); // returns Hi Ramesh because person object becomes "this" inside sayHi function.
var sayHiNewFunction = sayHi.bind(person); // creates a new function binding passed in object to "this".
Read this article http://hangar.runway7.net/javascript/difference-call-apply where the author explained about call and apply in such a simple way!!!
Also read this article http://hangar.runway7.net/javascript/guide from the same author.
You can pass additional parameters (comma separated) to call. The first param is considered as the object and the other parameters as parameters.
You can pass first parameter and additional parameters (in the form of array) to call. The first param is considered as the object and the array of parameters is taken in as additional parameters.
You can pass first parameters and additional parameters to bind. It creates a new function with the first param as the object and the rest of the params as params.
call - for comma separated params
array - for array form of params
bind - a new function
Read more: https://codeplanet.io/javascript-apply-vs-call-vs-bind/
No comments:
Post a Comment