Array|JavaScript 预解析( 二 )
直接上预解析后的代码:function num(){alert(num);}num = 1;num();
文章图片
文章图片
预解析是分作用域的
声明提升并不是将所有的声明都提升到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中的文字说明 , 条件式函数声明的处理和函数表达式的处理方式一样 , 所以条件式函数声明没有声明提升的特性 。
推荐阅读
- 自营区|跨界视聊为你解析:实体店生意难做,如何借助线上平台开店引流拓客?
- 国际足球|解析西班牙名单:上强度要速度,斗牛士紧跟时代潮流
- 驱动中国|“每5.4秒就有一场宠物直播”——解析快手宠物的内容生意经
- |履带移动破碎机特点及优势解析(全液压、油电混动版)
- 小米手机,雷军|全景解析小米10超大杯,雷军为何敢用“至尊”来全名?
- 行业互联网|解析未来天线技术与5G移动通信
- Array|臭氧层正在愈合,并对大气环流造成重大影响
- Array|瞄准“宅经济”!VR看房成年轻人租房新趋势
- Array|Spanlite公司使用3D打印一次高速烧结8,000个零件
- Array|面面俱到的绝佳体验 优质国产旗舰手机推荐
