Friday, January 26, 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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...