JavaScript:在对象构造函数中避免'this'被事件覆盖?

时间:2018-05-12 05:45:56

标签: javascript object constructor this

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

function Bar() {
	this.string = "something";
	this.event = function(e) {
		console.log("This should say something: " + this.string);
	}
}

var foo = new Bar();

window.addEventListener("mouseover", foo.event);

问题是'this.string'在'this.event'中变得未定义,因为事件监听器改变'this'来改为引用该事件。

我需要一种方法让它来打印“某事”。

任何帮助都将受到高度赞赏!

3 个答案:

答案 0 :(得分:4)

使用箭头函数,以便内部函数不会为其this获取新的上下文。



function Foo() {
	this.string = "something";
	this.event = (e) => {
		console.log("This should say something: " + this.string);
	}
}

var bar = new Foo();

window.addEventListener("mouseover", bar.event);




另一种选择是将this.event函数显式绑定到实例化对象:



function Foo() {
  this.string = "something";
  this.event = function(e) {
    console.log("This should say something: " + this.string);
  }.bind(this);
}

var bar = new Foo();

window.addEventListener("mouseover", bar.event);




您还可以在分配侦听器时绑定它:

window.addEventListener("mouseover", bar.event.bind(bar));

答案 1 :(得分:3)

bind foo foo.event

function Bar() {
  this.string = "something";
  this.event = function(e) {
    console.log("This should say something: " + this.string);
  }
}

var foo = new Bar();

window.addEventListener("mouseover", foo.event.bind(foo));

答案 2 :(得分:2)

除了给定的答案之外,还可以使用简单的局部变量来完成。

按照建议,以及使用Babel进行编译时这是一个箭头功能,这将转化为。



function Bar() {
	var _this = this;
	this.string = "something";
	this.event = function(e) {
		console.log("This should say something: " + _this.string);
	}
}

var foo = new Bar();

window.addEventListener("mouseover", foo.event);