我知道可以像这样扩展 CoffeeScript 类:
Dog::bark = ->
console.log("bark")
我希望能够动态地做到这一点。例如,我想做这样的事情:
sounds = [ "bark", "woof", "grrr", "ruff" ]
for sound in sounds
Dog::[sound] = ->
console.log(sound)
等效的 JavaScript 将是:
var sounds = [ "bark", "woof", "grrr", "ruff" ];
for (var i = 0; i < sounds.length; i++)
{
var sound = sounds[i];
Dog.prototype[sound] = function() {
console.log(sound);
};
}
如何使用 CoffeeScript 做到这一点?