You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:避免对象构造函数中的this被事件监听器覆盖

解决事件监听器中this指向丢失的问题

嗨,我完全懂你遇到的困扰——当你把对象的方法直接绑定为事件监听器时,this的指向会从原来的实例对象(也就是foo)切换成触发事件的元素(这里是window),自然就找不到this.string了。下面给你几个实用的解决办法:

方法1:用bind()固定this指向

bind()方法会创建一个新函数,把this永久绑定到你指定的对象上,不管后续怎么调用这个函数,this都不会跑偏。修改后的代码如下:

function Bar() { 
  this.string = "something"; 
  this.event = function(e) { 
    console.log("This should say something: " + this.string); 
  } 
}
var foo = new Bar();
// 把event方法的this绑定到foo实例
window.addEventListener("mouseover", foo.event.bind(foo));

方法2:用箭头函数定义事件方法

箭头函数不会绑定自己的this,它会继承外层作用域的this(也就是构造函数里的foo实例)。这样定义的话,事件触发时this就始终指向实例:

function Bar() { 
  this.string = "something"; 
  // 箭头函数继承构造函数的this上下文
  this.event = (e) => { 
    console.log("This should say something: " + this.string); 
  } 
}
var foo = new Bar();
window.addEventListener("mouseover", foo.event);

方法3:提前用变量保存this

在构造函数里把当前实例的this存成一个变量(比如self或者that),然后在事件方法里用这个变量访问实例属性,就绕开了this指向变化的问题:

function Bar() { 
  var self = this; // 保存当前实例的引用
  this.string = "something"; 
  this.event = function(e) { 
    console.log("This should say something: " + self.string); // 用self替代this
  } 
}
var foo = new Bar();
window.addEventListener("mouseover", foo.event);

这三种方法都能帮你输出预期的"something",选哪种全看你的代码习惯哦~

内容的提问来源于stack exchange,提问作者MysteryPancake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:24:36