I want to be able to write:
generate 'Cat', 'meow'
and define the generate function in such a way that it produces:
class Cat
meow: ->
@.__proto__.constructor.name + ' says meow.'
so that I can write:
garfield = new Cat
garfield.meow() # "Cat says meow"
If you don’t mind polluting your global namespace, I actually got this snippet running in the ‘try coffeescript’ runner at the CoffeeScript site:
Not 100% what you asked for, but it’s almost what you wanted, isn’t it?
Edit: Actually, the first script only worked in the browser, not the (
Node.js-based) CLI, corrected the script.If you know you’ll only live in the browser, you can loose
root.Catand only sayCat, but if you want Node.js and browser compat, you’ll have to live withroot.*Edit 2: It’s generally a better idea to return the class from the generating function rather than magically putting it in a namespace. It’s also possible to make the method names dynamic. With some inspiration from @Loren, the asker (notice how it doesn’t need to refer the global object anymore):