如何访问CoffeeScript类中的arguments.callee?

我有以下代码

class Foo a: -> console.log arguments.callee.name b: -> @a() c: -> @a() f = new Foo fb() #=> should output 'b' fc() #=> should output 'c' 

问题:我怎样才能得到我class上的调用函数的名字?


这是一个用例

 class Something extends Stream foo: -> _helper 'foo', 'a', 'b', 'c' bar: -> _helper 'bar', 'my neighbor totoro' dim: -> _helper 'dim', 1, 2, 3 sum: -> _helper 'sum', 'hello', 'world' _helper: (command, params...) -> @emit 'data', command, params... something = new Something something.foo() something.bar() # ... 

我不想重复发送每个调用的方法名称到我的私人_helper方法

所以要清楚,我认为你拥有这个方法的第二个方法是完全合理的,而且是一条路。

但是要回答您的问题,您可以dynamic生成每个function,以避免重新input命令。

 class Foo commands = foo: ['a', 'b', 'c'] bar: ['my neighbor totoro'] dim: [1,2,3] for own name, args of commands Foo::[name] = -> @emit 'data', name, args... 

并假设你想要的function有用的东西,你仍然可以使用function。

 // ... commands = foo: (args...) -> return ['a', 'b', 'c'] // ... for own name, cb of commands Foo::[name] = (command_args...) -> args = cb.apply @, command_args @emit 'data', name, args... 

这是我会做的:

 class Something extends Stream constructor: -> @foo = helper.bind @, "foo", "a", "b", "c" @bar = helper.bind @, "bar", "my neighbor totoro" @dim = helper.bind @, "dim", 1, 2, 3 @sum = helper.bind @, "sum", "hello", "world" helper = (command, params...) -> @emit 'data', command, params... 

这种方法的优点是:

  1. helper函数是一个私有variables。 它不能通过实例直接访问。
  2. helper函数只声明一次,并在所有实例之间共享。
  3. 函数foobardimsumhelper 部分应用程序 。 因此,它们不会为函数体消耗更多的内存。
  4. 它不需要像@ loganfsmyth的答案那样的循环。
  5. 它更干净。

编辑:一个更清洁的方法将是:

 class Something extends Stream constructor: -> @foo = @emit.bind @, "data", "foo", "a", "b", "c" @bar = @emit.bind @, "data", "bar", "my neighbor totoro" @dim = @emit.bind @, "data", "dim", 1, 2, 3 @sum = @emit.bind @, "data", "sum", "hello", "world" 

当然,这有点多余,但是你不能期待更多像JavaScript这样的语言。 这不是因素 。 然而它是可读的,干净的,容易理解的,而且最重要的是 – 正确的。