Creating a Ruby-style each() for JavaScript
Yep, this is another post that modifies built-in prototypes for JavaScript to add functionality I wish was already there.
I’ve been learning Ruby lately and I’ve really fallen in love with the idea of “blocks” and the way they’re used in that language. I thought it could be useful to introduce some of the functions that use blocks from Ruby into JavaScript using function objects.
This code adds a .each() function to every object in the runtime:
Object.prototype.each = function(fn){
var scope = arguments.length > 1 ? arguments[1] : window;
for(var i in this){
if(this[i] instanceof Function)
continue;
if(fn.call(scope, this[i], i) == false)
break;
}
return this;
};
Let’s walk through what’s going on here:
- Give all objects a new function called “each” by giving
Object.prototypea new function called “each”. Leteachaccepts at least one argument:fn, a function object. - If more than one argument was specified, define the second argument to be the scope within which we’ll call the function. Otherwise, set the scope to the
windowobject. - Iterate through every member of
this, the object on whicheach()was invoked:- Skip the member if it’s a function object itself (we only want to iterate over non-functions).
- Call the function within the defined
scopeand with two parameters: the member itself, and it’s identifier. - If the function returns false, interpret this as a signal to stop iterating.
- Return the object on which
each()was invoked, to support function chaining.
What are some other features you’ve created “translations” for a language based on another language?