Friday, August 31, 2018

What is the difference between call and apply method in jQuery




I have seen lot of java-script code,that uses call as well as apply methods to invoke the function.
I am little bit confuse about the exact difference and in what which one to use in what condition.


Answer



They're not jQuery things, they're JavaScript things.



They do the same thing: They call the given function using a specific value for this within the function call. The only difference is how you specify the arguments to pass to the function. With call, you specify them as a series of discrete arguments (after the first one, which is what to use as this). With apply, you specify them as an array (again after the first arg, which is what to use as this).



So say we have:



function foo(a, b, c) {
console.log("this = " + this);
console.log("a = " + a);
console.log("b = " + b);
console.log("a = " + c);
}


These two calls do exactly the same thing:



foo.call("bar", 1, 2, 3);
// Note --------^--^--^--- a series of discrete args

foo.apply("bar", [1, 2, 3]);
// Note ---------^-------^-- args as an array


In both cases, we see:




this = bar
a = 1
b = 2
c = 3

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...