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

Why does this change to the Array prototype not work in my jQuery plugin?

本文关键字:jQuery 我的 插件 不起作用 Array 原型 为什么      更新时间:2023-09-26

我在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插件中没有定义它?

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

Mozilla 的解释

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

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

arguments不是一个数组,而是一个对象。例如,它提供诸如arguments.calleearguments.caller之类的属性。

您可以通过调用Array原型的apply来使用它的foreach(参见JavaScript arguments object…及其后):

由于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;
}

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

试试这个:

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;
}

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

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