Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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

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

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

Object # has no method 'foreach'

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

like image 759
maxedison Avatar asked Jan 29 '12 13:01

maxedison


People also ask

Can I use array prototype at ()?

Array.prototype.at() The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

What does array prototype do?

The Array.prototype.group() methods can be used to group the elements of an array, using a test function that returns a string indicating the group of the current element.

What is prototype jQuery?

All objects have a prototype property. It is simply an object from which other objects can inherit properties. The snippet you have posted simply assigns an object with some properties (such as init ) to the prototype of jQuery , and aliases jQuery.prototype to jQuery.fn because fn is shorter and quicker to type.

What does every() do in JavaScript?

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.


1 Answers

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

Explanation from Mozilla

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)
like image 136
Hemlock Avatar answered Nov 15 '22 00:11

Hemlock