Friday, 26 January 2018

javascript - 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?


Answer



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)

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...