html - JavaScript Hoisting declaration confusion when using Immediately-invoked function expression -
get confused.
var message = "xinrui ma"; var call = (function(){ message = "i cool"; })(); alert(message);
from perspective, code treated this:
var message = "xinrui ma"; var call = (function(){ var message; // add message declaration here message = "i cool"; })(); alert(message); // should alert "xinrui ma", not "i cool", // cause hoisting javascript's default behavior of moving declarations // top of current scope
but in fact, outputs "i cool", why that????
if don't have variable declaration inside function, uses variable containing scope. doesn't create new local variable -- there wouldn't way refer closure variables if did that.
this has nothing hoisting, occurs when declare variable in function. hoisting apply if wrote:
var call = (function() { message = "i cool"; var message; })();
in case, var
declaration hoisted top of function.
Comments
Post a Comment