🟡JavaScript严格模式

本文最后更新于:2023年7月28日 凌晨

开启严格模式

全局开启

在脚本首行标记'use strict'开启全局严格模式

1
2
'use strict'
// ToDo
1
2
3
4
<script>
'use strict'
// ToDo
</script>

全局使用严格模式导入没有启用严格模式的库时可能会不兼容

函数单独开启

在函数首行标记'use strict'函数语块开启严格模式

1
2
3
4
function fn() {
'use strict'
// ToDo
}

默认的开启

es6语法中强制使用严格模式

严格模式的优势

  1. 可以对静默错误报错
  2. 优化了代码执行效率
  3. 对未来的保留关键字语法约束

严格模式的特性

严格模式会对以下行为会执行报错

禁止隐式全局变量声明

原先赋值未定义的变量时默认声明全局变量的行为被禁止

1
2
3
4
5
6
'use strict'
let myName
myName = 'Jonathan'
myNeme = 'Jonathan'
// > Uncaught ReferenceError: myNeme is not defined
// 可以解决意外的变量名书写错误(第二个myName拼错)

禁止删除变量名

1
2
3
4
'use strict'
const myName = 'Jonathan'
delete myName
// > Uncaught main.js:3

禁止同名形参

1
2
3
4
5
6
7
'use strict'
console.log(sum(1, 2, 3))
// > Uncaught main.js:5

function sum (a, a, b) {
return a + a + b
}

禁止使用前导0表示八进制

应使用es6语法表示八进制(使用前缀0o0O)

1
2
3
4
'use strict'
const num = 010
console.log(num)
// > Uncaught main.js:2

禁止对对象执行违规操作

禁止对只读属性赋值

1
2
3
4
5
6
7
8
'use strict'
const nums = {}
Object.defineProperty(nums, 'a', {
value: 1,
writable: false
})
nums.a = 2
// > Uncaught TypeError: Cannot assign to read only property 'x' of object '#<Object>'

禁止删除不可删除属性

1
2
3
4
5
6
7
8
'use strict'
const nums = {}
Object.defineProperty(nums, 'a', {
value: 1,
configurable: false
})
delete nums.a
// > Uncaught TypeError: Cannot delete property 'a' of #<Object>

禁止拓展不可拓展对象

1
2
3
4
5
6
7
'use strict'
const nums = {
x: 1
}
Object.preventExtensions(nums)
nums.y = 2
// > Uncaught TypeError: Cannot add property y, object is not extensible

禁止在块级作用域声明全局函数

在非严格模式下会输出两个1

1
2
3
4
5
6
7
8
9
10
'use strict'
if(true) {
function fn () {
console.log(1)
}
fn()
}
fn()
// > 1
// > Uncaught ReferenceError: fn is not defined

🟡JavaScript严格模式
https://qingshaner.com/JavaScript严格模式/
作者
清山
发布于
2022年2月23日
许可协议