function - Javascript ReferenceError: min is not defined -
i'm trying wrap head around anonymous , named functions , have javascript code here:
travelnode = min = function(travelnode) { console.log(travelnode); if(travelnode.left === null) return travelnode; else return min(travelnode.left); }(travelnode.right);
when try , run block, referenceerror: min not defined
. however, when change code this:
travelnode = function min(travelnode) { console.log(travelnode); if(travelnode.left === null) return travelnode; else return min(travelnode.left); }(travelnode.right);
and works fine.
obviously, first 1 uses anonymous functions , second named function. however, why second 1 work first 1 doesn't? how fix first one?
edit: here's entire code block -
delete: function(data) { var deletehelper = function(travelnode) { if(travelnode === null) return null; if(data < travelnode.data) travelnode.left = deletehelper(travelnode.left); else if(data > travelnode.data) travelnode.right = deletehelper(travelnode.right); else { if(travelnode.right === null) return travelnode.left; else if(travelnode.left === null) return travelnode.right; travelnode = min = function(travelnode) { console.log(travelnode); if(travelnode.left === null) return travelnode; else return min(travelnode.left); }(travelnode.right); } return travelnode; }; this.root = deletehelper(this.root); }
var g = function f() { ... }
scope f
inside function (so undefined outside it); assigned g
outside (which has scope on insides of it). result, can call function f
inside, , g
both inside , outside. f
safe tampering, since has value in closure; while g
can redefined, potentially breaking code.
in second example, min
defined inside function (but not outside it); since use inside not outside, works.
in first example, make anonymous function. invoke (travelnode.right)
. function executes, , breaks (since min
not yet assigned). if function complete without error, return value have been assigned both min
, travelnode
(just y = x = math.sqrt(4)
assigns 2
x
, y
after evaluating math.sqrt
).
you use parentheses, , make work:
travelnode = (min = function(travelnode) { console.log(travelnode); if(travelnode.left === null) return travelnode; else return min(travelnode.left); })(travelnode.right);
here, construct anonymous function, assign value min
, invoke it; since min
assigned , in scope, still works.
arguably, second approach best, given use min
inside; has added benefit debugging, since function not show anonymous in stack traces.
Comments
Post a Comment