关于 js 里面 this 的指向问题(6种场景)

可以分为6种情况来描述this指向

1. 普通函数直接调用中的this

function fun() {
   console.log(this);  // window
   function fn() {
       console.log(this);  // window
   }
   fn();
}
fun();
复制代码

如上代码函数里面直接调用会指向 window,需要注意的是在严格模式下this会指向 undefined

2. 在对象里调用的this

let obj = {
   name: '温情',
   fn() {
     console.log(this);  // {name: "温情", fn: ƒ}
   }
}
obj.fn();
复制代码

指向调用函数的那个对象,this: 谁调用我,我就指向谁

3. 在构造函数以及类中的this

function Person(name) {
  this.name = name;
  console.log(this);  // Person {name: "温情"}
}

Person.prototype.playGame = function() {
  console.log(this);  // Person {name: "温情"}
}

let wq = new Person('温情');
wq.playGame();
复制代码

构造函数配合 new 使用, 而 new 关键字会将构造函数中的 this 指向实例化对象,所以构造函数中的 this 指向 wq 这个实例对象

4. 绑定事件函数的this

<button>点击按钮</button>

const btn = document.querySelector('button');

btn.addEventListener('click', function() {
  console.log(this);  // btn
});
复制代码

this 指向 btn 这个按钮,谁调用就指向谁。

5. 定时器中的this

const btn = document.querySelector('button');

btn.addEventListener('click', function () {
  setTimeout(function() {
      console.log(this);  // window
  }, 1000);
  setTimeout(() => console.log(this), 1000);  //<button>点击按钮</button>
});
复制代码

第一个定时器中的 this 指向 window,因为定时器中采用回调函数作为处理函数,而回调函数的 this 指向 window,但是第二个定时器为什么指向 btn 按钮?因为使用了箭头函数,下面就看看箭头函数的 this 指向

6. 箭头函数中的this

var num = 10;

function fn() {
  var num = 20;
  setTimeout(() => {
      console.log(this.num);  // 10
  }, 100)
}
fn();
复制代码

箭头函数没有自己的 this,会继承父作用域的 this。

上面代码箭头函数的 this 继承 fn() 的 this,因为 fn 普通函数的 this 指向 window,所以此箭头函数指向 window,又因为 var 的变量会挂载到 window 对象上,所以 this.num 输出 10。(注意:这里不用 var 用 let 或 const 的话输出结果为 undefined), 不懂可以看 var、let、const 的区别

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享