调用方法的事件宽度JS OOP(原型)

Call Method By Event width JS OOP (prototype)

本文关键字:OOP 原型 JS 方法 事件 调用      更新时间:2023-09-26

我希望任何人都能帮助我=)

我尽量使这个例子保持简单:

function myClass(){
//some Code
}
myClass.prototype.func1 = function(){
//some Code
}
myClass.prototype.func2 = function(){
   document.getElementById("myEl").onclick = function(){
      this.func1 //does not work, this is only the Element...
   }
}

如何调用func1?我想在func2中绑定onclick-event

首先,必须保持对当前对象的引用。正如您已经注意到的,在事件处理程序中,this引用DOM元素。你可以使用

var self = this;
第二,你必须真正地调用函数:
self.func1();

完整的示例:

myClass.prototype.func2 = function(){
   var self = this;
   document.getElementById("myEl").onclick = function(){
      self.func1();
   };
}

在较新的浏览器中,您还可以使用.bind() [MDN]来明确定义this应该引用的内容(参见MDN文档中的其他浏览器的shim):

document.getElementById("myEl").onclick = this.func1.bind(this);

onclick函数中,this值绑定到被单击的元素。您需要在func2:

内部保留this的副本(引用)。
myClass.prototype.func2 = function(){
    var self = this; //keep a reference to the this value
    document.getElementById("myEl").onclick = function(){
        self.func1();
    }
}