关于JavaScript的严格模式

110 阅读3分钟

在前端开发中,经常会在很多框架的文件头部看到'use strict'字样,这个是什么意思呢?

图片1.png

从字面意思来看,是'使用严格',也即这个框架文件以严格的条件运行.

什么是严格模式?

由于JavaScript语法不够严谨,⼀直为⼈们所诟病.'use strict'是ECMAScript5(ES5)新增的.

在严格模式下,JavaScript对语法要求会更严格,⼀些在正常模式下可以正常运行的代码,在严格模式下不 能运行.

使用严格模式,主要好处有:

  • 将⼀些JS代码静默错误改为抛出错误,能更有效保障代码的运行安全

  •  消除⼀JS语法不合理的地方

  • 提高JS程序的运行效率

  • 为后续的JavaScript版本做好准备

支持严格模式的浏览器 Internet Explorer 10 + 、   Firefox 4+ 、   Chrome 13+ 、   Safari 5.1+ 、   Opera 12+。

怎么启用严格模式?

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Document</title>
</head>

<body>
   <script>
       // 在JavaScript脚本的开头写上'use strict'或者"use strict"
      // 代表这个JavaScript脚本都处于严格模式
     'use strict';
  </script>

</body>

</html>

或者

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Document</title>
</head>

<body>
   <script>
     function x() {
         //在函数中的第⼀⾏写'use strict',表示只在当前函数启⽤严格模式
        'use strict';
       }
    </script>
</body>

</html>

严格模式相关规定

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

'use strict'

// 运⾏代码会抛出ReferenceError: name is not defined 异常
// ReferenceError: name is not defined
name = '杰烽教育'

// 正确写法为:
let name = '杰烽教育'

2.不允许删除变量或函数

'use strict'

// 运⾏代码会抛出SyntaxError: Delete of an unqualified identifier in strict mode.
let person = {name: '⼩明', age: 18}
delete person

// 运⾏代码会抛出SyntaxError: Delete of an unqualified identifier in strict mode.
 function run() {
     console.log('每天早上要跑步')
}
 delete run

3.不允许函数的参数同名

// 运⾏代码会抛出SyntaxError: Duplicate parameter name not allowed in this context
function add(a, a) {
   return a + a
 }

4.不允许使⽤⼋进制

// 运⾏代码会抛出SyntaxError: Octal literals are not allowed in strict mode.
let x = 010

5.不允许使⽤转义字符

// 运⾏代码会抛出SyntaxError: Invalid or unexpected token
2 let x = \010

6.不允许对只读属性赋值

let obj = {}

// 运⾏代码会抛出TypeError: Cannot assign to read only property 'name' of object '#<Object>'

Object.defineProperty(obj, 'name', {value: '⼩明', writable: false})

obj.name = '⼩红'

7.不允许对⼀个使⽤getter⽅法读取的属性进⾏赋值

// 运⾏代码会抛出TypeError: Cannot set property name of #<Object> which has only a getter
let obj = {
    get name() {
       return '⼩明'
    }
}

obj.name = '⼩红'

8.不允许删除⼀个不允许删除的属性

// 运行代码会抛出TypeError: Cannot delete property 'prototype' of function Object() {[native code] }
delete Object.prototype

9.变量名不能使用“eval”字符串或者“arguments”字符串

// 运行代码会抛出SyntaxError: Unexpected eval or arguments in strict mode 
// let eval = '今天天气不错'  
let arguments = '今天天⽓不错'

10.不允许使用with语句

// 运行代码会抛出SyntaxError: Strict mode code may not include a with statement 
with (Math) {
  x=cos(2)
}

11.eval 语句的作⽤域是独⽴的

// 运⾏代码会抛出ReferenceError: x is not defined
eval('let x = 520')
console.log(x)

12.禁⽌使⽤ this 表示全局对象

function run() {
     console.log(this)
}
// 运⾏代码返回undefined
// 在普通模式下,this 关键字表示全局对象 window,⽽在严格模式下,this关键字则表示undefined。
 run()

软件开发-IT培训-人才输送 @杰烽科技