maxedison maxedison - 1 year ago 50
jQuery Question

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;

that.bind(event[0], function(){
.bind(event[1], function(){

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
method works in other places of my code. Why is it undefined within this jQuery plugin?

Answer Source

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 =