应用jquery小部件(this,arguments)

Kag*_*awa 3 javascript jquery jquery-widgets

有时我看到有人用这个来调用小部件中的函数

this.myFunction.apply(this, arguments);
Run Code Online (Sandbox Code Playgroud)

而不是这个:

this.myFunction();
Run Code Online (Sandbox Code Playgroud)

什么是.apply jQuery函数?

somefunction.apply(thisobj, argsarray)
Run Code Online (Sandbox Code Playgroud)

上面调用函数somefunction,在函数范围内将其设置为thisobj,并将argsarray中的参数作为函数的参数传递.

但考虑到下面的情况,无论是直接调用函数还是使用.apply()都不一样?我已经看到一些教程偏爱.apply()方法,包括jQuery网站本身.http://jqueryui.com/demos/widget/

这是一个小部件'标准'还是还有其他我缺少的东西?

_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!");
    }
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 8

apply方法只允许您指定函数的上下文,它还允许您将参数作为数组提供.从精细手册:

调用具有给定this值的函数并arguments作为数组提供.

arguments作为数组提供是重要的.调用函数的当前参数在类数组arguments对象中可用,实际参数独立于函数的签名; 例如,f = function() {...}可以调用as ,如果需要f(1,2,3),f可以将这三个值拉出来arguments.

所以这:

that.displayMessage.apply(that, arguments);
Run Code Online (Sandbox Code Playgroud)

调用that.displayMessage具有相同参数的_create 调用,而不_create需要知道(或关心)调用它的参数; 这允许函数在调用链的中间滑动,而不必用可能不同数量的参数进行调整.这与仅仅打电话完全不同that.displayMessage().

如果_create被称为这样:

o._create('where is', 'pancakes house?');
Run Code Online (Sandbox Code Playgroud)

那么这个apply电话相当于:

that.displayMessage('where is', 'pancakes house?');
Run Code Online (Sandbox Code Playgroud)

但如果使用不同的参数:

o._create(1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

那么apply就好像我们这样做了:

that.displayMessage(1, 2, 3);
Run Code Online (Sandbox Code Playgroud)