jquery widget apply(this, arguments)

Kagawa picture Kagawa · Apr 29, 2012 · Viewed 7.4k times · Source

Sometimes I see people using this to call function within a widget

this.myFunction.apply(this, arguments);

instead of this:

this.myFunction();

What's the .apply jQuery function?

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.

But considering the case below, wouldn't it be the same whether calling the function directly or using .apply()? I've seen a few tutorials favor .apply() method instead, including the jQuery site itself. http://jqueryui.com/demos/widget/

Is this a widget 'standard' or is there something else that i'm missing?

_create: function() {
            var that = this;
            this.myButton = $( "<button>", {
                text: "My Button"
            })
            .appendTo( this.element )
            .bind("click", function() {
                // _bind would handle this check
                if (that.options.disabled) {
                    return;
                }
                that.displayMessage.apply(that, arguments);
                // Why not just call the following?
                // that.displayMessage();
            });
        },
displayMessage: function() {
        alert("Hey!");
    }

Answer

mu is too short picture mu is too short · Apr 29, 2012

The apply method does a little more than allow you to specify the context for a function, it also allows you to supply the arguments as an array. From the fine manual:

Calls a function with a given this value and arguments provided as an array.

The arguments provided as an array is important. The current arguments that a function was called with are available in the array-like arguments object and the actual arguments are independent of the function's signature; for example, f = function() {...} can be called as f(1,2,3) and f can pull those three values out of its arguments if it wants.

So this:

that.displayMessage.apply(that, arguments);

calls that.displayMessage with the same arguments that _create was called with without _create needing to know (or care) what parameters it was called with; this allows a function to slip itself in the middle of the call chain without having to muck about with possibly different numbers of parameters. This is quite different than just calling that.displayMessage().

If the _create was called like this:

o._create('where is', 'pancakes house?');

then the apply call is equivalent to:

that.displayMessage('where is', 'pancakes house?');

but if different parameters were used:

o._create(1, 2, 3);

then the apply would act as though we did this:

that.displayMessage(1, 2, 3);