严格模式
严格模式即在严格的条件下运行,是ECMAScript5新增的一种运行模式。
IE10之前的版本不支持该模式。
严格模式的目的
- 消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为;
- 消除代码运行的一些不安全之处,保证代码运行的安全;
- 提高编译器效率,增加运行速度;
- 为未来新版本的Javascript做好铺垫。
开启严格模式
1、 全局开启
在所有语句之前声明 " use strict " ;(或 ‘ use strict ’ ;)
2、 局部开启
给某个函数开启严格模式,需要在函数内部所有语句前声明 " use strict " ;
(function(){
"use strict";
// 严格模式
})();
(function(){
//平常模式
})();
严格模式的规则
以下是严格模式下常见的几个规则
1、变量声明必须有var关键字,不允许再意外创建伪全局变量。
// (function(){
// a = 10;
// console.log(a); // 10
// })();
(function(){
"use strict";
a = 10; // 引用错误 ReferenceError: a is not defined
})();
2、函数的形参不允许重复
// (function(){
// //不规范的写法
// function foo(a,a,b){
// console.log(a,b);//正常执行 2 3
// }
// foo(1,2,3);
// })();
(function(){
"use strict";
function foo(a,a,b){
console.log(a,b);
//SyntaxError: Duplicate parameter name not allowed in this context
// 语法错误:不允许同名参数存在于同一个作用域
}
foo(1,2,3)
})();
3、严格模式下,arguments和形参的关系进行了分离
// arguments 会受到 形参赋值的影响
// (function(){
// function foo(a,b){
// a = 20;
// console.log(a,b);// 20 2
// console.log(arguments[0],arguments[1]);//20 2
// // 在非严格模式下,函数的arguments和当前函数定义的形参存在映射关系,一个变另外一个也变
// }
// foo(1,2)
// })();
(function(){
"use strict";
// 形参 和 arguments 之间的区别:
// 形参是变量可以随意赋值
// arguments 就是对应实参的关键字,获取所有的实参,进行使用,不会受形参影响
function foo(a,b){
a = 20;
console.log(a,b); // 20 2
console.log(arguments[0],arguments[1]); // 1 2,不再受到形参的影响
}
foo(1,2)
})();
4、不允许使用arguments的callee、caller等属性
// (function(){
// function foo(){
// // arguments.callee 指向当前的函数
// console.log(arguments.callee);//打印出foo(){}
// }
// foo()
// })();
(function(){
"use strict";
function foo(){
// 禁用了部分arguments的属性
console.log(arguments.callee)//类型错误 TypeError
}
foo()
})();
5、this指向windows时,会让this的指向抛空
// (function(){
// function foo(){
// console.log(this);// this 指向window
// }
// foo()
// })();
(function(){
"use strict";
function foo(){
// 禁用指向window的this,此时打印为undefined
console.log(this);
}
foo()
})();
6、禁用了with(){}语句
// 使用with语句语法会混乱,会很大程度上降低代码的性能
// (function(){
// with(Math){
// console.log(random()); //相当于Math.random
// console.log(PI); //相当于Math.PI
// }
// })();
(function(){
"use strict";
// 严格模式之下不允许包含with(){}语句
with(Math){
console.log(random());
console.log(PI);
// 语法错误 SyntaxError: Strict mode code may not include a with statement
}
})();
7、不允许使用八进制
// (function(){
// console.log(012);//八进制012->十进制10
// })();
(function(){
"use strict";
console.log(012);//语法错误 SyntaxError: Octal literals are not allowed in strict mode.
})();
我们应当谨慎地使用严格模式,让代码更工整更规范。