Javascript在构造函数中将dom事件设置为prototype方法

Javascript seting dom event to prototype method in constructor

本文关键字:设置 prototype 方法 事件 dom 构造函数 Javascript      更新时间:2023-09-26

我遇到了一些Javascript问题,假设我们有一个构造函数

function test(element) {
  this.element = element;
  this.element.onfocus = function() { this.onfocus(); }
}
test.prototype.onfocus = function() {
  alert("focused");
}
new test(document.getElementByID("E1"));

所以我试图动态地设置内部构造函数的焦点事件,但它似乎不工作,我不能弄清楚。

有人帮助吗?

谢谢,

AJ

在JavaScript中,在this.element.onfocus = function() {this.onfocus(); }上下文中,second this是触发事件的元素。

换句话说,如果你想以正确的方式工作,你的代码应该像这样:

function test(element) {
  this.element = element;
  var currentObject = this;
  this.element.onfocus = function() {currentObject.onfocus(); }
}

不要认为JavaScript是一个体面的面向对象编程语言,因为它是面向原型的,它有一些薄弱的东西,比如影响你的代码。

你为什么不读一读这篇文章呢?我相信它会为你澄清这个关键字:
  • http://www.switchonthecode.com/tutorials/javascript-tutorial-why-the-this-keyword-breaks

必须存储对'this'的引用,因为onfocus函数在另一个上下文中,而'this'引用的是其他内容:

function test(element) {
  this.element = element;
  var that = this;
  this.element.onfocus = function() { that.onfocus(); }
}