I would like to generate functions in a loop:
for own k, v in t
ctor::[k] = ->
v(...)
@
However, coco seems to generate just one function and reuse it:
var k, v, __ref, __own = {}.hasOwnProperty;
for (k in __ref = t) if (__own.call(__ref, k)) {
v = __ref[k];
ctor.prototype[k] = __fn;
}
function __fn(){
v.apply(this, arguments);
return this;
}
How to change the coco script to make the output following:
var k, v, __ref, __own = {}.hasOwnProperty;
for (k in __ref = t) if (__own.call(__ref, k)) {
v = __ref[k];
ctor.prototype[k] = function() {
v.apply(this, arguments);
return this;
}
}
CLARIFICATION: With coco I mean this language: http://satyr.github.com/coco/ (a coffeescript fork).
It's a feature. Writing function
directly within a loop should be almost always avoided. JSLint forbids it saying "Don't make functions within a loop."
Your code in particular has a scope bug (all v
in the dynamically created methods will refer to the same value). You should use let
binding there:
for own k, v in t
let
ctor::[k] = ->
v ...
this
which compiles to:
var k, v, __ref, __own = {}.hasOwnProperty;
for (k in __ref = t) if (__own.call(__ref, k)) {
v = __ref[k];
(__fn.call(this, k, v));
}
function __fn(k, v){
ctor.prototype[k] = function(){
v.apply(this, arguments);
return this;
};
}