Array|JavaScript 预解析( 二 )


直接上预解析后的代码:function num(){alert(num);}num = 1;num();
Array|JavaScript 预解析
文章图片

文章图片

预解析是分作用域的
声明提升并不是将所有的声明都提升到window对象下面 , 提升原则是提升到变量运行的环境(作用域)中去 。function showMsg() {var msg = 'This is message'; } alert(msg); // msg未定义
还是直接把预解析之后的代码写出来:function showMsg() {var msg;msg = 'This is message'; } alert(msg); // msg未定义预解析是分段的
分段 , 其实就分script标签的
func();// 输出 AA2;function func(){console.log('AA1');}function func(){console.log('AA2');}
function func(){console.log('AA3');}
在上面代码中 , 第一个script标签中的两个func进行了提升 , 第二个func覆盖了第一个func , 但是第二个script标签中的func并没有覆盖上面的第二个func 。所以说预解析是分段的 。
tip:但是要注意 , 分段只是单纯的针对函数 , 变量并不会分段预解析 。函数表达式并不会被提升func();var func = function(){alert("我被提升了");};
这里会直接报错 , func is not a function , 原因就是函数表达式 , 并不会被提升 。只是简单地当做变量声明进行了处理 , 如下:var func;func();func = function(){alert("我被提升了");}条件式函数声明console.log(typeof func);if(true){function(){return 1;}}console.log(typeof func);
上面这段代码 , 就是所谓的条件式函数声明 , 这段代码在Gecko引擎中打印"undefined"、"function";而在其他浏览器中则打印"function"、"function" 。
原因在于Gecko加入了ECMAScript以外的一个feature:条件式函数声明 。Conditionally created functions Functions can be conditionally declared, that is, a function declaration can be nested within an if statement. Note: Although this kind of function looks like a function declaration, it is actually an expression (or statement), since it is nested within another statement. See differences between function declarations and function expressions.
Note中的文字说明 , 条件式函数声明的处理和函数表达式的处理方式一样 , 所以条件式函数声明没有声明提升的特性 。


推荐阅读