functionstrict(){// Function-level strict mode syntax'use strict';functionnested(){return"And so am I!";}return"Hi! I'm a strict mode function! "+nested();}functionnotStrict(){return"I'm not strict.";}
变更
严格模式影响了语法和语义。
把失误转为错误
防止无意间创建全局变量
123
'use strict';mistypedVariable=17;// 拼写失误或故意不用 var 来声明将抛异常
"use strict";// throws exceptionNaN=1;// Assignment to a non-writable propertyvarobj1={};Object.defineProperty(obj1,"x",{value:42,writable:false});obj1.x=9;// throws a TypeError// Assignment to a getter-only propertyvarobj2={getx(){return17;}};obj2.x=5;// throws a TypeError// Assignment to a new property on a non-extensible objectvarfixed={};Object.preventExtensions(fixed);fixed.newProp="ohai";// throws a TypeError
删除不可移除的属性时报错(以前是返回 false 表示不可移除)
12
"use strict";deleteObject.prototype;// throws a TypeError
"use strict";varf=function(){returnarguments.callee;};f();// throws a TypeError
更「安全」
函数中的 this 不再被强制装箱包装成对象,这意味着对于普通调用,this 将是 undefined 而不是非严格模式下的 global(浏览器中是 window)。
无法遍历调用栈,fn.caller、fn.arguments 等禁止访问
1234567891011
functionrestricted(){"use strict";restricted.caller;// throws a TypeErrorrestricted.arguments;// throws a TypeError}functionprivilegedInvoker(){returnrestricted();}privilegedInvoker();
禁止使用 arguments.caller
12345678
"use strict";functionfun(a,b){"use strict";varv=12;returnarguments.caller;// throws a TypeError}fun(1,2);// doesn't expose v (or a or b)