小编loo*_*ole的帖子

CoffeeScript动态方法

我正在尝试在咖啡脚本中动态创建方法,但正如我的代码所示,我用来创建方法的迭代器不会在迭代之间重置其变量,所以我想知道冲突的共享变量:

class MyClass
  constructor: (@name) ->

  for k, v of ['get', 'set']
    console.log('creating method: ' + v)
    MyClass::[v] = (args...) ->
      method = v
      console.log('executing method: ' + method)

o = new MyClass('dummy')
o.get()
o.set()
Run Code Online (Sandbox Code Playgroud)

输出:

> creating method: get
> creating method: set
> executing method: set
> executing method: set
Run Code Online (Sandbox Code Playgroud)

一个人知道我做错了什么?

metaprogramming coffeescript

6
推荐指数
2
解决办法
2476
查看次数

标签 统计

coffeescript ×1

metaprogramming ×1