Simple Metaprogramming in Javascript

'use strict'; function Dog() { this.name = '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'); fido.blue() // => Get the ball that is blue fido.red() // => 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 http://eewang.github.io/blog/2013/04/29/metaprogramming-ruby-and-antipatterns-in-rails/

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.