Why doesn't this change in the Array prototype work in my jQuery plugin?

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

To use this jQuery plugin, my code would look something like this:

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

However, the browser throws an error in the string "arguments.foreach (...." of the jQuery plugin, simply indicating that

Object # does not have a 'foreach' method

However, the foreach method works elsewhere in my code. Why is it undefined inside this jQuery plugin?

+4
source share
4 answers

This does not work because the arguments are not an array. Own object of arguments (array).

Explanation from Mozilla

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

 var argArray = Array.prototype.slice.call(arguments) 
+6
source

arguments not an array, but an object. For example, it provides properties such as arguments.callee and arguments.caller .

You can use the foreach prototype of Array by invoking apply on it (cf. JavaScript arguments object ... on ):

Since all Array.prototype methods are designed as general, they can easily be applied to an array-compatible argument object:

 jQuery.fn.addClassForEvents = function(){ var that = this; [].foreach.apply(arguments, (function(event){ that.bind(event[0], function(){ that.addClass(event[0]); }) .bind(event[1], function(){ that.removeClass(event[0]); }); }); return this; } 
+3
source

You need to rotate the arguments of the object to an array

Try the following:

 jQuery.fn.addClassForEvents = function(){ var that = this, arg = Array.prototype.slice.call(arguments); arg.foreach(function(event){ that.bind(event[0], function(){ that.addClass(event[0]); }) .bind(event[1], function(){ that.removeClass(event[0]); }); }); return this; } 
+1
source

To convert arguments to an array, you can use jQuery.makeArray(arguments) too ...

http://api.jquery.com/jQuery.makeArray/

0
source

Source: https://habr.com/ru/post/1393612/


All Articles