by yiransheng · 12y ago · 0 comments
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
}
vs. 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
}
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. function make_dot_product(dim) {
return (dim === 3) ? dot3 : dot2;
function dot3(a,b) {
return a.x*b.x+a.y*b.y+a.z*b.z
}
function dot2(a,b) {
return a.x*b.x+a.y*b.y
}
} function make_dot_product(dim) {
if (dim === 3) {
return function(a,b) {
return a.x*b.x+a.y*b.y+a.z*b.z
}
} else if (dim === 2) {
return function(a,b) {
return a.x*b.x+a.y*b.y
}
}
return null;
} function make_dot_product(dim) {
var dot;
if (dim === 3) {
dot = function(a, b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
};
} else if (dim === 2) {
dot = function(a, b) {
return a.x * b.x + a.y * b.y;
};
}
return dot;
}
This also makes it clearer what happens if neither dim is neither 2 nor 3.That said, it is cleaner to only 'var' each variable once, to suppress this confusion.