92

I see that in different plugins and codes, but I don't understand what does that function... In the jQuery api isn't referenced!

CRISHK Corporation
  • 2,948
  • 6
  • 37
  • 52
  • 21
    It's not in the jQuery reference, since it's a [ **native Javascript function** ](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply). – Peter Ajtai Sep 26 '10 at 07:12

2 Answers2

128

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.

Loïc Gammaitoni
  • 4,173
  • 16
  • 39
Amber
  • 507,862
  • 82
  • 626
  • 550
  • 2
    Related is the [ **.call() function** ](http://mdn.beonex.com/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call) that also takes a `this`, but it is followed by a series of individually listed arguments instead of an array containing the arguments. – Peter Ajtai Sep 26 '10 at 07:15
  • what will below do than? $.when.apply(null, object).done(callback); – Gohel Kiran Jan 12 '13 at 07:07
  • @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 – Luke Madhanga Jul 07 '14 at 14:03
  • Distantly related was the [jQuery proxy function](https://api.jquery.com/jQuery.proxy/), which is useful to change the value of `this` i.e. the context variable, the way Javascript's native `apply` can do – Nate Anderson Aug 17 '16 at 16:15
5

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.

issa marie tseng
  • 3,194
  • 22
  • 20
  • 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. – R. Schreurs Apr 16 '15 at 12:33
  • @R.Schreurs also you need to use the jQuery.fn object as seen here: http://stackoverflow.com/a/27374435/674033 – AVProgrammer Nov 15 '16 at 19:14