Simple Metaprogramming in Javascript

'use strict'; function Dog(name) { = name; } Dog.prototype.colors = function() { for(var i = 0; i < arguments.length; i++) { this[arguments[i]] = new Function('console.log( + " got the ' + arguments[i] + ' ball")'); } } var fido = new Dog('Fido'); fido.colors('blue', 'red'); // => Fido got the blue ball // => Fido got the red ball
Using the Function constructor is generally frowned upon, but this was too good to not try. I originally saw this in ruby at

Tell me what you think

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.