JavaScript 严格模式,use strict

前言:

"use strict" 指令在 JavaScript 1.8.5 (ECMAScript5) 中新增。

它不是一条语句,但是是一个字面量表达式,在 JavaScript 旧版本中会被忽略。

"use strict" 的目的是指定代码在严格条件下执行。

严格模式下你不能使用未声明的变量。

浏览器支持情况:

Internet Explorer 10 +、 Firefox 4+ Chrome 13+、 Safari 5.1+、 Opera 12+。

使用方式:

在脚本或函数的头部添加 "use strict"; 表达式来声明。

针对全局要求使用严格模式:

"use strict";
fo() { console.log('---') }

针对某个函数内部要求使用严格模式:

fo(){
  "use strict";
   console.log('---')
}

主要作用:

  1. 消除版本javascript中一些不合理及不严谨之处,减少怪异行为
  2. 提高编译效率,提高运行速度
  3. 为新版本的javasript做铺垫兼容

语法说明:

1.不允许使用未声明的变量:

"use strict";
x = 3.14; // 报错: Uncaught ReferenceError: x is not defined

2.不允许删除变量, 对象, 函数:

"use strict";
var x = 3.14;
delete x;               // 报错: Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.

3.不允许函数的参数重名:

"use strict";
function fo(x1, x1) {}; // 报错: Uncaught SyntaxError: Duplicate parameter name not allowed in this context

4.不允许使用八进制:

"use strict";
var x = \010;           // 报错: Uncaught SyntaxError: Invalid or unexpected token

5.不允许对只读属性赋值::

"use strict";
var obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});

obj.x = 3.14;           // 报错: Uncaught TypeError: Cannot assign to read only property 'x' of object '#<Object>'

6.不允许对一个使用getter方法读取的属性进行赋值:

"use strict";
var obj = {get x() {return 0} };

obj.x = 3.14;            // 报错: Uncaught TypeError: Cannot set property x of #<Object> which has only a getter

7.不允许删除一个不允许删除的属性:

"use strict";
delete Object.prototype; // 报错: Uncaught TypeError: Cannot delete property 'prototype' of function Object() { [native code] }

8.变量名不能使用 "eval" 字符串:

"use strict";
var eval = 3.14;         // 报错: Uncaught SyntaxError: Unexpected eval or arguments in strict mode

9.变量名不能使用 "arguments" 字符串:

"use strict";
var arguments = 3.14;    // 报错: Uncaught SyntaxError: Unexpected eval or arguments in strict mode

10.禁止this关键字指向全局对象:

function f(){
    return !this;
} 
f() // 返回false,因为"this"指向全局对象,"!this"就是false

function f(){ 
    "use strict";
    return !this;
} 
f() // 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。

因此,使用构造函数时,如果忘了加new,this不再指向全局对象,而是报错:

function f(){
    "use strict";
    this.a = 1;
};
f();// 报错,this未定义

  var a = function() {

    console.log(this)

  }

  a() // 输入window  

  var b =new a() //输出a对象

特别提示: "use strict" 指令只允许出现在脚本或函数的开头。