"use strict";var name = "Reeoo";console.log(name);BUT这种写法存在天然的坑,假如我们要做代码合并,我现在要把heigui.js:
heigui = "db";和reeoo.js进行合并,本来两个脚本分开执行是好好的,合起来就会报错。
(function(){ "use strict"; var name = "reeoo";})();(function(){ heigui = "db";})();这样合并之后就不会报错了。function strictFun(){ // 函数级别严格模式语法 "use strict"; console.log("I am a strictmode function!");}function normalFun() {console.log("I am a mormal function!");}Chrome中调试严格模式"use strict"name = "reeoo";console.log(name)把这段代码直接粘贴到Chrome的控制台中执行,正常情况下应该报错,但是并没有报错,

很显然,严格模式下变量不适用var声明是不合法的,但是为什么没有报错?
这是什么鬼,难道Chrome不支持严格模式?开什么玩笑。。。
网上搜了一下,原来Chrome的控制台的代码是运行在eval之中的,你没法对eval函数使用严格模式(应该也不完全对,但是具体Chrome做了什么,不得而知),下图说明eval函数可以使用严格模式:

要想在Chrome浏览器中对严格模式正常报错,需要在代码外层套一个立即执行函数,或者其它类似的措施。
(function(){ "use strict" name = "reeoo"; console.log(name) })()这样就可以了
严格模式到底有多严格
严格模式中一些重要的限制
1、变量声明
不允许使用一个没有声明的变量
"use strict";name = "reeoo";报错(代码草稿纸,下同)
"use strict";var testObj = Object.defineProperties({}, { prop1: { value: 10, writable: false // 一个只读的属性 }, prop2: { get: function () { } }});testObj.prop1 = 20; //尝试改变prop1的值testObj.prop2 = 30;//尝试改变prop2的值严格模式下会报错:"use strict";var testObj = new Object();Object.preventExtensions(testObj);//经过这个方法处理过的对象,不影响原有对象的删除,修改.但是无法添加新的属性成员了.testObj.name = "reeoo";严格模式报错:
"use strict";var testvar = 15,testObj={};function testFunc() {};delete testvar;delete testFunc;Object.defineProperty(testObj, "testvar", { value: 10, configurable: false });delete testObj.testvar;报错:"use strict";var testObj = { prop1: 10, prop2: 15, prop1: 20};报错(node控制台)"use strict";function testFunc(param1, param1) { return 1;};报错:"use strict";var testoctal = 010;var testescape = 10;报错:
"use strict";function testFunc() { return this;}var testvar = testFunc();在非严格模式下,testvar 的值为全局对象window,但在严格模式下,该值为 undefined。"use strict";var eval = "hehe";Uncaught SyntaxError: Unexpected eval or arguments in strict mode
"use strict";var arr = [1, 2, 3, 4, 5];var index = null;for (index in arr) { function myFunc() {};}node控制台:"use strict";eval("var testvar = 10");console.log(testvars);Uncaught ReferenceError: testvar is not defined
"use strict";var arguments = 1;Uncaught SyntaxError: Unexpected eval or arguments in strict mode
"use strict";function testArgs(oneArg) { arguments[0] = 20;}在非严格模式下,可以通过更改 arguments[0] 的值来更改 oneArg 参数的值,从而使 oneArg 和 arguments[0] 的值都为 20。在严格模式下,更改 arguments[0] 的值不会影响 oneArg 的值,因为 arguments 对象只是一个本地副本。"use strict";function my(testInt) { if (testInt-- == 0) return; arguments.callee(testInt--);}my(100);用了的下场就是这样:"use strict";with (Math){ x = cos(3); y = tan(7);}Uncaught SyntaxError: Strict mode code may not include a with statement