##严格模式下需要注意的点:
全局变量显式声明
直接调用函数this指向undefined
delete删除全局变量会报错
对象不能有重名的属性
函数不能有重名的参数
对arguments做了限制
1. 不允许对arguments赋值2. arguments不再追踪参数的变化
函数必须声明在顶层
新增了保留字
implements, interface, let, package, private, protected, public, static, yield
开启严格模式的好处:
严格模式 “strict mode”
使用严格模式可以消除js语法上不合理,不严谨,减少怪异的行为
开启严格模式:
在一对script标签的开始使用字符串 “use strict”在函数中使用字符串 ‘use strict’
在严格模式下,使用以下的注意点:
1.直接调用函数,函数中的this就不指向window了,而是undefined
//非严格模式下,this指向windowfunction fn(){console.log(123,this)//打印出:123,window};fn();//严格模式下,this指向,写谁就是谁function fn1(){"use strict"//严格模式console.log(123,this)//打印出:123,undefinedde };fn1();
2.使用call第一参数改变this指向,在es5中指向是window,在严格模式下执行传入的第一个参数
//call/apply方法一旦使用都可以直接调用函数;//非严格模式下,this指向windowfunction fn(){console.log(123,this)};fn.call();//严格模式下,this指向,写谁就是谁function fn1(){"use strict"console.log(123,this)//打印出:123,this;如果不给call传参数,this是undefined};fn1.call(null);
3. 形参不能重复声明,重复声明会报错
//非严格模式下,后声明的a覆盖之前的,function fn5(a,a){return a*a;};console.log(fn5(2,3));//打印出:9//严格模式下,this指向,写谁就是谁function fn4(a,a){"use strict"return a*a;};fn4(2,3)//报错:(Uncaught SyntaxError: Duplicate parameter name not allowed in this context)
4. arguments不能追踪变化
// 当形参发生变化时候,arguments会追踪变化// 当开启严格模式之后,arguments就不在追踪形参变化了// arguments是实参的集合(类数组)//非严格模式下:function fn8(a){a=10;console.log(arguments)//打印出来的是10;在函数体内被改变过后的值;};fn8(3);//严格模式下,形参不要重复定义,否则会报错function fn9(a){"use strict"a=10;//?????写在开启严格模式之前,打印出来的还是10;console.log(arguments)//打印出来的是3;也就是调用时传进来的实参的值};fn9(3);
5. 不允许对arguments赋值
//非严格模式下function fun1(a,b){arguments = 10;console.log(arguments)//打印出10;可以赋值;};fun1(1,2);//严格模式下:function fun2(a,b){//"use strict"arguments = 10;console.log(arguments)//不允许赋值,直接报错:Uncaught SyntaxError: Unexpected eval or arguments in strict mode};fun2(1,2);
6. 声明变量必须显式的使用var let const来声明变量,不用关键字声明会报错
function fun3() {"use strict"aini = 'dada';};fun3();//直接报错:Uncaught ReferenceError: aini is not defined at fun3;
7. 试图用delete删除变量会报错
//直接报错:Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.(function (){"use strict"var abc = 'hhhhh';delete abc; })();
8. 函数声明必须在顶层或函数作用域中,在非函数的代码块中会报错
注:不能再for,if,while语句中声明函数;
//非严格模式下if(false){function fat(){console.log(1)}};console.log(fat)//打印undefined,为true时,打印fat这个函数;//严格模式下,不能再for,if,while中声明函数"use strict"if(true){function fat1(){console.log(1)}};fat1();//直接报错:Uncaught ReferenceError: fat1 is not defined
参考:[/blog//01/javascript_strict_mode.html
/enUS/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode][1]