CPPAlien / JS-QA

前端知识问答
0 stars 0 forks source link

use strict 几大作用 #43

Open CPPAlien opened 3 years ago

CPPAlien commented 3 years ago

防止 this 默认指向 window

function test() {
  console.log(this)  //window
}

function test() {
  'use strict'
  console.log(this)  // undefined
}

不允许使用未声明的变量

function test() {
  count = 1;    // test 执行后,因为 count 未声明,会被挂载到 window 上,
}
'use strict'
function test() {
  cd = 1
}
test()
////
VM234:3 Uncaught ReferenceError: cd is not defined
    at test (<anonymous>:3:6)
    at <anonymous>:5:1

eval 的限制

使用 use strict 后,eval 内部创建的变量和函数无法被外部访问。给 eval 关键字赋值也会导致错误。