An example case where "var" method is useful:<p><pre><code> function make_dot_product(dim) {
if (dim === 3) {
var dot = function(a,b) {
return a.x*b.x+a.y*b.y+a.z*b.z
}
} else if (dim === 2) {
var dot = function(a,b) {
return a.x*b.x+a.y*b.y
}
}
return dot
}
</code></pre>
vs.<p><pre><code> function make_dot_product(dim) {
if (dim === 3) {
function dot(a,b) {
return a.x*b.x+a.y*b.y+a.z*b.z
}
} else if (dim === 2) {
function dot(a,b) {
return a.x*b.x+a.y*b.y
}
}
return dot
}
</code></pre>
The second case is erroneous, as it will always return 2-dimensional dot function (even if you call make_dot_product(20)). The is because function nameSpace() is defined at parse time, so inside the make_dot_product scope, two instance of dot functions are created, with the second overwriting the first. If we use var f = function() {...} this can be avoided.