Simple Metaprogramming in Javascript

'use strict'; function Dog() { = 'Fido'; } Dog.prototype.colors = function() { for(var i = 0; i < arguments.length; i++) { this[arguments[i]] = new Function('console.log(" Get the ball that is ' + arguments[i] + '")'); } } var fido = new Dog(); fido.colors('blue', 'red'); // => Get the ball that is blue // => Get the ball that is red
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.