我们可以通过 ‘use strict’ 开启严格模式,严格模式和非严格模式下有一些特殊的地方,这里我们简要列举几点:

# 变量

非严格模式下可以这样创建全局变量

a = 1

严格模式下则不行

'use strict'
b = 1  // Uncaught ReferenceError: b is not defined

严格模式下不能使用保留关键字做为变量名

'use strict'
let interface = 1 // Uncaught SyntaxError: Unexpected strict mode reserved word

# 函数

非严格模式下,修改函数命名参数的值,这个修改也会反映到 arguments 对象上

function fn(a, b) {
  a = 2;
  console.log(a) // 2
  console.log(arguments[0]) // 2
}
fn(1, 2)

严格模式下,命名参数和 arguments 是独立的

function fn(a, b) {
  a = 2;
  console.log(a) // 2
  console.log(arguments[0]) // 1
}
fn(1, 2)

# call、apply、bind

在非严格模式下使用函数的 apply、call、bind 时,null 或 undefined 值会被转换为全局对象。

var color = 'red';
function Color(color) {
  this.color = color
}
Color.prototype = {
  getColor() {
    console.log(this.color)
  }
}
const c = new Color('blue')
c.getColor() // blue
c.getColor.call(null) // red
c.getColor.call(undefined) // red
c.getColor.call(window) // red
const f = c.getColor.bind(null)
f() // red

在严格模式下,函数的 this 值为调用 call、apply、bind 指定的值。

'use strict'
var color = 'red';
function Color(color) {
  this.color = color
}
Color.prototype = {
  getColor() {
    console.log(this.color)
  }
}
const c = new Color('blue')
c.getColor() // blue
c.getColor.call(null) // Uncaught TypeError: Cannot read property 'color' of undefined
c.getColor.call(undefined) // Uncaught TypeError: Cannot read property 'color' of undefined
const f = c.getColor.bind(null) // Uncaught TypeError: Cannot read property 'color' of undefined
f()

c.getColor.call(window) // red

# 其他

严格模式中不能使用 with 语句。

<!-- 非严格模式 -->
<script>
  with(location) {
    console.log(href) // file:///Users/sun/Desktop/base/js-base/use-strict/1.html
  }
</script>
<!-- 严格模式 -->
<script>
  'use strict'
  with(location) { // Uncaught SyntaxError: Strict mode code may not include a with statement
    console.log(href) 
  }
</script>

严格模式中不能使用八进制

<!-- 非严格模式 -->
<script>
  var value = 010;
  console.log(value) // 8
</script>
<!-- 严格模式 -->
<script>
  'use strict'
  var value = 010;
  console.log(value) // Uncaught SyntaxError: Octal literals are not allowed in strict mode.
</script>

参考:

非严格模式 🆚 严格模式的区别|附思维导图 (opens new window)