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?
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.
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.
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.
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With