生成原型方法
Generating prototype methods
我正在尝试在 coffeescript class 上生成方法,如下所示:
class Test
log: (msg...) ->
for m in msg
console.log(m)
for alias in ['one', 'two', 'three', 'four', 'five']
Test::[alias] = (v...) ->
o = {}
o[alias] = v[0]
Test::log.apply(@, [o].concat(v.slice(1)))
t = new Test()
t.one(1)
t.two(3)
出于我完全无法理解的原因,打印出来
{ five: 1 }
{ five: 2 }
而不是我的预期,是:
{ one: 1 }
{ two: 2 }
我在这里错过了什么?
问题是您在 for
循环的每次迭代中将 alias
变量绑定到新值。因此,当调用 t.one(1)
方法时 alias
变量绑定到 'five'
.
有两种方法可以解决这个问题。
第一个解决方案是使用 Array.prototype.forEach():
['one', 'two', 'three', 'four', 'five'].forEach (alias) ->
Test::[alias] = (v...) ->
// ..
第二种解决方案是使用 coffee-script do
语句创建闭包:
for alias in ['one', 'two', 'three', 'four', 'five']
Test::[alias] = do (alias) -> (v...) ->
// ..
我正在尝试在 coffeescript class 上生成方法,如下所示:
class Test
log: (msg...) ->
for m in msg
console.log(m)
for alias in ['one', 'two', 'three', 'four', 'five']
Test::[alias] = (v...) ->
o = {}
o[alias] = v[0]
Test::log.apply(@, [o].concat(v.slice(1)))
t = new Test()
t.one(1)
t.two(3)
出于我完全无法理解的原因,打印出来
{ five: 1 }
{ five: 2 }
而不是我的预期,是:
{ one: 1 }
{ two: 2 }
我在这里错过了什么?
问题是您在 for
循环的每次迭代中将 alias
变量绑定到新值。因此,当调用 t.one(1)
方法时 alias
变量绑定到 'five'
.
有两种方法可以解决这个问题。
第一个解决方案是使用 Array.prototype.forEach():
['one', 'two', 'three', 'four', 'five'].forEach (alias) ->
Test::[alias] = (v...) ->
// ..
第二种解决方案是使用 coffee-script do
语句创建闭包:
for alias in ['one', 'two', 'three', 'four', 'five']
Test::[alias] = do (alias) -> (v...) ->
// ..