5 ms·
function doTree(node, fn) { fn(node.value); for (var i = 0; i < node.children.length; ++i) { doTree(node.children[i], fn); }
by bhiggins 16y ago
function doTree(node, fn) {
fn(node.value);
for (var i = 0; i < node.children.length; ++i) {
doTree(node.children[i], fn);
}
}
var sum = 0;
doTree(numTree, function(value) { sum += value; });
- RiderOfGiraffes 16y agoI don't know JS at all, so I'm interested in this example. Can you really pass in a function like this and have the referencing to the variable "sum" work as you would want? Can someone explain (or point to an explanation of) the scoping rules for me? Thanks.
- drewolson 16y agoIn javascript, functions are closures. This means that the function "closes" over the environment in which it was defined. In the above example, the function has access to the sum variable because it was available at the time the function was defined. It is then free to add to that variable when the function is called at a later time.