javascript严格模式

javascript运行模式有两种,除了平时使用的正常模式外,还有一种严格模式,顾名思义,就是在更严格的模式下运行。

严格模式的好处有很多:避免一些怪异行为以及不规范行为、提高编译效率等。

要使用严格模式只需要在当前执行环境的顶部写以下代码:

<script>
    'use strict';
</script>

一般在项目中是这样写的:

(function(){
  'use strict';
})()

这样有助于代码合并,并且不影响他人的代码。

下面说下严格模式的一些限制。

1、不允许未声明的全局变量。

str = 'hello';
str; //Uncaught ReferenceError: s is not defined

2、禁止使用with语句。

var o = {};
with(o){} //Uncaught SyntaxError: Strict mode code may not include a with statement

3、创建eval作用域。

var x = 2;
console.info(eval("var x = 5; x")); // 5
console.info(x); // 2

4、this的指向。

function f(){
   return !this;
} 
// 返回false,因为"this"指向全局对象,"!this"就是false
function f(){ 
  "use strict";
  return !this;
} 
// 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。

5、禁止删除变量,除非configurable设置为true。

var x;
delete x; // 语法错误
var o = Object.create(null, {'x': {
  value: 1,
   configurable: true
}});
delete o.x; // 删除成功

6、对象不能有重名的属性,函数不能有重名的参数。

var o = {
  p: 1,
  p: 2
}; // 语法错误
function f(a, a, b) { // 语法错误
  return ;
}

7、禁止使用arguments.callee。

var f = function() { return arguments.callee; };
f(); // 报错

还有很多个人觉得不太常用的在严格模式下会报错的语法,这里就不再赘述。

 参考自:http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html

posted @ 2016-12-20 10:59  _Jo  阅读(116)  评论(0编辑  收藏  举报