ECMAScript5之StrictMode

时间:2023-03-09 03:51:39
ECMAScript5之StrictMode

ECMAScript5引入一个严格模式的概念(Strict Mode)。

它的作用就是不让Javascript的容错那么高,让我们对编写代码的规范要求高一点。

比如,当我们使用严格模式编写JavaScript代码时,我们不能隐式的申明变量,必须带var。

那怎么使用严格模式(Strict Mode)呢?

当我们想让代码启动严格模式(Strict Mode)时,我们可以在代码的开头或者函数function的开头中添加”use strict”。

倘若我们在整个代码中启用严格模式(Strict Mode),那么所有代码都必须遵循严格模式的规范;

倘若我们在一个function中启用,那么只在这个function中,得遵循严格模式的规范。

我们一起来写个demo,体验体验下。

<!DOCTYPE html>
<head>
<title>strict mode</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
//启用严格模式
"use strict";
function testFunction(){
var testvar = 4;
return testvar;
}
//This causes a syntax error.
testvar = 5;
</script>
</body>
</html>

在上面的demo中,我在整个代码中启用严格模式,但我在function的外部声明变量时,没有加var,因此不符合严格模式规范,所以运行代码时会报错。

ECMAScript5之StrictMode

哈,有点意思。

刚才我们是在整个代码中启用严格模式,下面我们再来写个demo,在function里启用严格模式。

<!DOCTYPE html>
<head>
<title>strict mode</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
function testFunction(){
"use strict";
testvar = 4;
return testvar;
}
testvar = 5;
</script>
</body>
</html>

打开chrome调试器:

ECMAScript5之StrictMode

纳尼!!怎么没有报错?!!

我们再看看上面的代码,哈哈哈,原来是我们没有调用testFunction嘛,既然没执行它,它怎么会启用严格模式呢?

修改代码如下:

<!DOCTYPE html>
<head>
<title>strict mode</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
function testFunction(){
"use strict";
testvar = 4;
return testvar;
}
//调用testFunction
testFunction();
testvar = 5;
</script>
</body>
</html>

再看看chrome结果:

ECMAScript5之StrictMode

哇咔哇咔,严格模式还是挺严格的嘛,如果我们在写代码中,想启用的严格模式,那就得注意咯。

下面列举了在严格模式下的几个重点限制:

JavaScript

限制

例子

变量

使用一个变量,但是没有用var去声明

    testvar = 4;

delete

删除一个变量,函数或者agrument

    var testvar = 15;

    function testFunc(){}

    //causes fault

    delete testvar;

    delete testFunc;

属性名

在声明对象时,重复使用一个属性名

    var testObj = {

     prop1: 10,

    prop2: 15,

    //causes fault

    prop1: 20

    }

参数名

在函数参数中,重复使用一个参数名

function testFunc(param1,/*causes fault*/param1){

return 1;

}

有潜力成为关键字

在未来有可能成为有用的关键字,不能用来作为变量名或者函数名

    implements

    interface

    package

    private

    protected

    public

    static

    yield

八进制数

将八进制数赋给一个变量

    var testoctal = 010;

    var testescape = \010;

this

当this为null或者undefined的时候,它是不能被转换成全局对象(window)的

    function testFunc(){

    return this;

    }

    var testvar = testFunc();

在不是严格模式下,这个testvar的值是全局对象,但在严格模式下,它的值却是undefined.

eval,arguments

eval,arguments不能作为函数名或者参数名、变量名

    var eval = 10;

    var arguments =10;

arguments

在函数中,我们不能通过改变arguments,来改变对应参数值

    function testArgs(oneArg){

    arguments[0] = 20;

    }

在非严格模式下,我们如果想改变oneArg,可以通过Arguments[0]来改变,如上代码这样,执行后,oneArg和Arguments[0]的值都是20;但是在严格模式下,我们不能通过arguments来改变参数名的值,arguments仅仅是一个拷贝而已。

arguments.callee

不允许这么使用

    function(testInt){

      if(testInt-- == 0){

      return;

         }

         arguments.callee(testInt);

     }