为什么会发生这种变化Array的prototype对象不是在我的jQuery插件工作? [英] Why does this change to the Array prototype not work in my jQuery plugin?

查看:86
本文介绍了为什么会发生这种变化Array的prototype对象不是在我的jQuery插件工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经添加下面的方法来了Array原型:

I have added the following method to the Array prototype:

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

在同一文件的之后的上述code,我有以下的jQuery插件:

In the same file, after the above code, I have the following jQuery plugin:

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插件,我的code看起来是这样的:

In order to use this jQuery plugin, my code would look something like:

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

但是,浏览器抛出的错误arguments.foreach(....的jQuery插件线,说明仅仅是

However, the browser throws an error on the "arguments.foreach(...." line of the jQuery plugin, stating simply that

对象#没有法的foreach

Object # has no method 'foreach'

然而,的foreach 方法的工作在我的code的其他地方。为什么这个jQuery插件中未定义?

Yet the foreach method works in other places of my code. Why is it undefined within this jQuery plugin?

推荐答案

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

It doesn't work because arguments isn't an array. Its an (array-like) arguments object.

从Mozilla的说明

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

You can convert it to an array using slice in modern browsers (and by actually looping in IE).

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

这篇关于为什么会发生这种变化Array的prototype对象不是在我的jQuery插件工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆