CoffeeScript Dynamic Methods

I am trying to dynamically create methods in a coffee script, but, as my code shows, the iterator that I use to create methods does not reset its variables between iterations, so I fit into common variables that have 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 

Does anyone know what I'm doing wrong?

+6
source share
2 answers

Your internal function:

 (args...) -> method = v console.log('executing method: ' + method) 

is actually a closure on v , so when it is executed, v will evaluate its last value in the loop (i.e. set ). Looks like you just need to sort out the closure a bit:

 build_method = (v) -> (args...) -> method = v console.log('executing method: ' + method) 

And then:

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

Keep in mind that CoffeeScript is just JavaScript with a different make-up, so it experiences a lot of problems (like any language with closure), and these problems have the same solutions.

+5
source

mu correctly diagnosed the problem. The most immediate solution is to use the do keyword for the CoffeeScript language, which creates and runs an internal function that captures the values ​​of the variables you pass in:

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

I will talk about this feature in my PragPub article, A CoffeeScript Intervention .

+7
source

Source: https://habr.com/ru/post/891568/


All Articles