What is the difference between .apply and .call

I often use jQuery objects with regular js objects; I am trying to figure out how I can use .call and .pap more often in my scripts when necessary. I tested the code to see how it works.

However, when I run my code below (which essentially just hides all the divs on the page) in firebug on sites that I know have jQuery, I get a variety of results; I am wondering if this is jQuery version or this code is just “buggy”, I have to decrypt why .call always works, but .apply doesn't think it will be the other way around, based on the code below

var myApp = {} // instantiate an empty objct myApp.hide = function (whatever) { that = whatever $(that).hide() } var Numbers = function (object) { this.object = object; } Numbers.prototype.div = $('div'); var numbers = new Numbers(); numbers.div myApp.hide.call(numbers, numbers.div) myApp.hide.apply(numbers, numbers.div) 

When I run the code above or using .call or .apply, I get a different result depending on the site. Each site running jquery.call will work, but for some sites, such as jQuery.com and twitter, both will use .apply and .call, but other sites, such as the New York Times and Netflix, will work. only .call. I assume this is a jQuery version that makes a difference, but a bit confusing because numbers.div always returns an array of all div elements on the page, so I think this will work all the time. Any explanation is appreciated as I still understand the concepts of .call and .apply. I always refer to Douglas Crockford's book, but to be honest, he does not go into details about .apply and .call

+4
source share
2 answers

.apply you need to pass the arguments as an array.

SO

 myApp.hide.call(numbers, numbers.div) 

should be the same as

 myApp.hide.apply(numbers, [numbers.div]) 

But your myApp.hide function myApp.hide not have this , so the first parameter .call or .apply may be something else, it does not matter.

+4
source

The strength of the call / application really is that the Context you want this to be in the called function. The first parameter determines what it will be. They are a good example of how in Javascript functions it does not matter when / where the function is called, but how. (So, in your case it will be numbers )

Both .apply() and .call() work independently, the second parameter for any of them is actually optional.

As everyone says, the only real difference between them is whether you want to pass arguments / parameters as an array (a numeric array Array [], not an associative array {}).

.apply(contextYouWant, [oneParam, twoParam, etc]);

Or in the case of .call() you pass the parameters individually.

.call(contextYouWant, oneParam, twoParam, etc);

+2
source

All Articles