看代码:

//定义一个可见的盒子用于绑定点击事件
var box = document.getElementById('box');
box.x = 'box'

//设置执行函数的对象属性
function outFunc() {
  this.x = 'outFunc';
  box.addEventListener('click', func, false);
}
outFunc();

function func() {
  console.log(this.x); //输出box 说明该this指向的是调用addEventListener的对象
}

代码2:

function outFunc() {
  this.x = 'outFunc';//给全局对象window.x赋值(相当于赋值全局变量)
  box.addEventListener('click', func.bind(this), false);
}
function func() {
  console.log(this.x); //输出outFunc 使用bind设置this的值
}

总结,使用bind绑定的事件才是指向函数,否则指向的是调用addEventListener的对象。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-13
  • 2022-12-23
  • 2021-04-10
  • 2021-06-18
  • 2021-09-30
  • 2022-12-23
猜你喜欢
  • 2021-12-19
  • 2022-12-23
  • 2021-12-24
  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案