如何使用类方法作为回调在类中添加事件处理程序?
<div id="test">move over here</div>
<script>
oClass = new CClass();
function CClass()
{
this.m_s = "hello :-/";
this.OnEvent = OnEvent;
with(this)
{
var r = document.getElementById("test");
r.addEventListener('mouseover', this.OnEvent); // this does NOT work :-/
}
function OnEvent()
{
alert(this); // this will be the HTML div-element
alert(this.m_s); // will be undefined :-()
}
}
</script>
是的,我知道一些使其工作的怪癖,但是当引入这些事件处理程序时,预期的方式是什么???我再次有一种痛苦的感觉,没有人真正生活在 OOP 中 :-(
在这里给你玩:https : //jsfiddle.net/sepfsvyo/1/