Closures And CoffeeScript's Scoping
The following code defines two functions, lines and circles, that return a function, f and g respectively. Functions f and g are equal (() -> size) only for simplicity, but in g
Solution 1:
You can't use a helper function in your code, as that won't have access to the closure variable as expected. However, you can wrap your whole code in a function so that it returns you the lines
or circles
function respectively:
make = (def, accessor) ->
() ->
size = def
f = () -> accessor size
f.size = (_) ->
size = _
f
f
lines = make 10, (size) -> size
circles = make 15, (size) -> size
Solution 2:
You can define a factory function to produce your individual "constructors":
shape = (defaultSize, calculate = (size) -> size) ->
() ->
size = defaultSize
f = () -> calculate size
f.size = (_) ->
size = _
f
f
lines = shape(10)
circles = shape(15, (size) -> size * size * Math.PI)
This compiles to:
var circles, lines, shape;
shape = function(defaultSize, calculate) {
if (calculate == null) {
calculate = function(size) {
return size;
};
}
return function() {
var f, size;
size = defaultSize;
f = function() {
return calculate(size);
};
f.size = function(_) {
size = _;
return f;
};
return f;
};
};
lines = shape(10);
circles = shape(15, function(size) {
return size * size * Math.PI;
});
console.log(lines()());
console.log(lines().size(20)());
console.log(circles()());
console.log(circles().size(30)());
Post a Comment for "Closures And CoffeeScript's Scoping"