JavaScript:避免';这';在对象构造函数中是否被事件覆盖?

JavaScript:避免';这';在对象构造函数中是否被事件覆盖?,javascript,object,constructor,this,Javascript,Object,Constructor,This,我想不出一个直截了当的题目来回答这个问题。我可以用代码更好地解释它: 功能条(){ this.string=“某物”; this.event=函数(e){ log(“这应该是说:“+This.string”); } } var foo=新条(); window.addEventListener(“mouseover”,foo.event)改用箭头函数,这样内部函数就不会为其this获取新的上下文 函数Foo(){ this.string=“某物”; 此事件=(e)=>{ log(“这应该是说

我想不出一个直截了当的题目来回答这个问题。我可以用代码更好地解释它:

功能条(){
this.string=“某物”;
this.event=函数(e){
log(“这应该是说:“+This.string”);
}
}
var foo=新条();

window.addEventListener(“mouseover”,foo.event)改用箭头函数,这样内部函数就不会为其
this
获取新的上下文

函数Foo(){
this.string=“某物”;
此事件=(e)=>{
log(“这应该是说:“+This.string”);
}
}
var bar=newfoo();
window.addEventListener(“mouseover”,bar.event)foo与
foo.event

功能条(){
this.string=“某物”;
this.event=函数(e){
log(“这应该是说:“+This.string”);
}
}
var foo=新条();

addEventListener(“mouseover”,foo.event.bind(foo))我不知道您是否有意避免这种情况,但您只需传递一个匿名函数作为事件的处理程序,然后在那里调用
foo.event()

您可以按照其他人的建议使用
bind()
和arrow函数,但您也可以简单地这样做

功能条(){
this.string=“某物”;
this.event=函数(e){
log(“这应该是说:“+This.string”);
}
}
var foo=新条();
addEventListener(“mouseover”,function()){
foo.event();

});除了给定的答案,还可以使用简单的局部变量来完成

正如所建议的,当使用Babel编译时,例如,这是一个箭头函数,它将转换为什么

功能条(){
var_this=这个;
this.string=“某物”;
this.event=函数(e){
log(“这应该是说:”+_This.string);
}
}
var foo=新条();

window.addEventListener(“mouseover”,foo.event)谢谢!我可能会使用第二个选项,因为如果可能的话,我不能使用ES6,不要因为浏览器不兼容而限制自己使用旧版本的Javascript编写—如果您允许自己使用最新、最优雅的Javascript版本编写,然后在构建过程中自动将其转换为与旧版本的浏览器兼容,那么您将使编写变得更简单。