I’m trying to create methods dynamically in coffee script, but as my code shows, the iterator I use to create the methods doesn’t reset its variables between iterations and so I en up with shared variables that conflicts:
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()
Outputs:
> creating method: get
> creating method: set
> executing method: set
> executing method: set
one knows what I’m doing wrong?
Your inner function:
is actually a closure on
vso when it is executed,vwill evaluate to its last value in the loop (i.e.set). Looks like you just need a bit of closure busting:And then:
Keep in mind that CoffeeScript is just JavaScript with different makeup so it suffers from a lot of the same problems (as does any language with closures) and those problems have the same solutions.