jquery widget apply(this, arguments)

javascript, jquery, jquery-widgets

Solution

It is not jQuery, it's JavaScript. `.apply()` and `.call()` allow you to change what `this` means inside the function.

Problem

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!"); } ```

Original source

Related problems