I have implemented each function like this in JS:
Object.prototype.each = function(fn){
for (var x in this){
if (this.hasOwnProperty(x)){
fn(x);
}
}
return this;
};
var o = {'a' : 'apple', 'b' : 'bat', 'c' : 'cat'};
o.each(function(i){
alert(i);
});
Though this works fine. Is there anything wrong in it. Asking because I am learning JS.
Also why does it produces error if I do:
{'a' : 'apple', 'b' : 'bat', 'c' : 'cat'}.each(function(i){
alert(i);
});
You need to put parentheses around the object or it will interpret it as a block due to the opening and closing curly brackets.
When you do it without the parentheses, the interpreter will “see” this:
Which is a block with a single expression. However, since that is not a valid expression it will return a syntax error. Even if it were a valid expression, it would still give you an error since blocks do not have properties and therefore the dot property access notation is not applicable:
Thus, you need to tell the interpreter that the object is an expression by wrapping it in parentheses to remove the ambiguity (since you cannot put a statement inside a parentheses – only expressions).