js 严格模式

js严格模式下的this指向

(全局作用域下的函数this指向由window变为undefined;定时器函数的this还是指向window)

1、严格模式下全局作用域下的函数this指向undefined

(function () {
  console.log(this);// 指向window
}())

  (function () {
    "use strict"
    console.log(this);// 指向undefined
  }())

2、非严格模式下的构造函数不加new当普通函数调用时,this指向window;

而严格模式下,这样使用this会报错(因为this指向undefined);如果是使用new实例化的构造函数,this还是指向对象实例

非严格模式
    function x() {
      this.name = 'name'
      console.log(this)// 指向window
    }
    x()
严格模式
    function x() {
      "use strict"
      this.name = 'name' // undefined.name='name',所以报错
      console.log(this)// 指向undefined
    }
    x()

3、严格模式下定时器函数的this依然指向window;

    "use strict"
    // 箭头函数的this指向上一层,这里是window
    setTimeout(() => {
      console.log(this); // 指向window
    }, 1000)

    // 定时器函数的this指向的是window
    setTimeout(function () {
      console.log(this); // 指向window
    }, 1000)
posted @ 2020-09-26 13:10  17135131xjt  阅读(140)  评论(0编辑  收藏  举报