I see that in different plugins and codes, but I don't understand what does that function... In the jQuery api isn't referenced!
What's the .apply jQuery function?
Asked Answered
It's not in the jQuery reference, since it's a [ native Javascript function ](developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…). –
Felipa
apply
calls a function with a set of arguments. It's not part of jQuery, it's part of core Javascript. However, there is mention of it in the jQuery docs:
http://docs.jquery.com/Types#Context.2C_Call_and_Apply
Syntax:
somefunction.apply(thisObj, [argsArray])
The above calls the function somefunction
, setting this
to thisObj
within the function's scope, and passing in the arguments from argsArray
as the arguments to the function.
Related is the [ .call() function ](mdn.beonex.com/en/Core_JavaScript_1.5_Reference/Global_Objects/…) that also takes a
this
, but it is followed by a series of individually listed arguments instead of an array containing the arguments. –
Felipa what will below do than? $.when.apply(null, object).done(callback); –
Vesting
@user1531437 That calls
$.when(object).done(callback);
, but in the function $.when
, this
is set to the first parameter, i.e. null
. Arguably, one should be using $.when.call(null, object).done(callback);
because the second parameter of .apply
is supposed to be an array –
Kamila Distantly related was the jQuery proxy function, which is useful to change the value of
this
i.e. the context variable, the way Javascript's native apply
can do –
Kelson Essentially, apply will call a function with the context being set to the object you apply the function to. This means that within the function, referencing this
will refer to that object.
For anyone working with jQuery and arriving at this answer, you'll need to use
$(this)
to get the associated jQuery object and have access to jQuery methods. –
Trashy @R.Schreurs also you need to use the jQuery.fn object as seen here: https://mcmap.net/q/1483191/-jquery-on-apply-not-working –
Mcclees
© 2022 - 2024 — McMap. All rights reserved.