如何理解 javascript代码 的 use strict 严格模式?
发布于 作者:苏南大叔 来源:程序如此灵动~
转眼间2017年就是js
的时代了,各种js
框架大行其道,百花怒放,nodejs
系列更是层出不穷。在高级别的js
里面,就经常看到use strict
这句代码,如下所示。那么这句话具体是做什么用的呢?
不知道大家有没有看过hacklang的严格模式,其实是差不多的。都是放在第一行(理论上的第一行,js里面是函数体第一行,hacklang里面,也允许前面有个shebang
行),都是”严格执行“(就是说报错的概率大大增加哦)。
在js
的严格模式下,在旧的js
解析器中,use strict
字样会被忽略,而在新版js
解析器中,使用了use strict
的js
文件中,不能使用未声明的变量。
示例代码
(function(){
"use strict";
//your code goes here
})();
实战例子
好吧,光说不练花把式。下面是个比较明显的例子,是最近在研究用"油猴脚本"加载piwik
统计代码的时候,碰到的例子,有"user strict”的时候,报错。
没有"user strict”的时候,顺利执行。
上面的对比说明,可以看出相关区别。苦乐滋味,自己品尝。
相关链接
附上大牛的相关文章:http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html ,大家看看更详细的说明吧。
总结
好好学习,天天向上。


