为什么这个更改为Array原型在我的jQuery插件中不起作用?

时间:2012-01-29 13:31:23

标签: javascript jquery arrays jquery-plugins prototype

我已将以下方法添加到Array原型中:

Array.prototype.foreach = function(func){
    for(var i = 0; i < this.length; i++){
        if(!func(this[i]) === false) break; //return false from func in order to break the loop
    }
    return this;
}

在同一个文件之后上面的代码中,我有以下jQuery插件:

jQuery.fn.addClassForEvents = function(){

    var that = this;

    arguments.foreach(function(event){
        that.bind(event[0], function(){
            that.addClass(event[0]);
        })
        .bind(event[1], function(){
            that.removeClass(event[0]);
        });
    });

    return this;
}

为了使用这个jQuery插件,我的代码看起来像:

$('div').addClassForEvents(['mouseenter', 'mouseleave']);

然而,浏览器在jQuery插件的“arguments.foreach(....”行引发错误,只是说明了

  

对象#没有方法'foreach'

然而,foreach方法适用于我的代码的其他位置。为什么在这个jQuery插件中未定义?

4 个答案:

答案 0 :(得分:7)

它不起作用,因为参数不是数组。它是一个(类似数组的)参数对象。

Explanation from Mozilla

您可以在现代浏览器中使用切片将其转换为数组(并在IE中实际循环)。

var argArray = Array.prototype.slice.call(arguments)

答案 1 :(得分:3)

arguments不是数组,而是对象。例如,它提供arguments.calleearguments.caller等属性。

您可以通过调用apply来使用数组原型的foreach(参见The JavaScript arguments object…and beyond):

  

由于Array.prototype的所有方法都是通用的,因此可以很容易地应用于与数组兼容的arguments对象:

jQuery.fn.addClassForEvents = function(){

    var that = this;

    [].foreach.apply(arguments, (function(event){
        that.bind(event[0], function(){
            that.addClass(event[0]);
        })
        .bind(event[1], function(){
            that.removeClass(event[0]);
        });
    });

    return this;
}

答案 2 :(得分:1)

您需要将参数对象转换为数组

试试这个:

jQuery.fn.addClassForEvents = function(){

    var that = this, arg = Array.prototype.slice.call(arguments);

    arg.foreach(function(event){
        that.bind(event[0], function(){
            that.addClass(event[0]);
        })
        .bind(event[1], function(){
            that.removeClass(event[0]);
        });
    });

    return this;
}

答案 3 :(得分:0)

要将arguments转换为数组,您也可以使用jQuery.makeArray(arguments) ...

http://api.jquery.com/jQuery.makeArray/

相关问题