javascript - Why defining function inside an if is a bad idea? -
from eloquent javascript marijn haverbeke
different javascript platforms in different browsers have traditionally done different things in situation, , latest standard forbids it.
but why bad?
function example () { function () {} // okay if ( ) { function b () {} // danger ! } }
it's considered "bad" because behavior inconsistent , doesn't people expect. consider following snippet:
if (true) { function f() { return "t"; } } else { function f() { return "f"; } } what calling f() return? on ie , firefox, return "t", on chrome , safari, return "f". why? combination of hoisting , javascript's scoping rules. information on how works, see this question on javascript scoping , hoisting.
effectively, means that, on browsers, branch ignored when comes function definitions using function name() { ... } form. if need (and don't, since poor style, anyway), use name = function () { ... } form instead, since not hoisted, behavior well-defined , not inconsistent across platforms.
Comments
Post a Comment