2

我知道可以像这样扩展 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 做到这一点?

4

1 回答 1

4

您几乎拥有它,您只需要在构建新方法时将 a 扔进do去以强制sound进行评估:

sounds = [ "bark", "woof", "grrr", "ruff" ] 
for sound in sounds
    do (sound) ->
        Dog::[sound] = -> console.log(sound)

如果你不包括do你最终会得到所有四种方法都在做console.log('ruff'). 添加dofor循环的主体转换为自执行函数。来自精美手册(本节底部):

当使用 JavaScript 循环生成函数时,通常会插入一个闭包包装器,以确保循环变量是封闭的,并且所有生成的函数不只是共享最终值。CoffeeScript 提供了do关键字,它立即调用传递的函数,转发任何参数。

演示:http: //jsfiddle.net/ambiguous/YAqJu/

于 2013-04-06T22:52:42.873 回答