Unusual javascript behavior -
i have encountered weird behavior in javascript. consider code:
var foo; function bar(){ function foo(){}; foo = 10; return; } foo = 1; bar(); console.log(foo); this output 1. if delete foo function declaration in third line, output 10. why isn't output 10 when function declaration there? , reason if change function definition this:
foo = function(){}; it output 10 again? know hoisting of function declarations, doesn't seem answer this.
that's not weird - have variable called foo, you're setting 1 normally. inside bar function, foo function
- if present, shadows variable
- if not present,
fooreferences original variable.
as such, if define foo function, foo=10 take effect on that, otherwise take effect on original foo.
as second part of question (why change if use var foo=...), that's because in case duplicate variable declaration merged one, end same if didn't write var.
Comments
Post a Comment