JavaScript 中是否有最佳实践或通用方法将类成员作为事件处理程序?
考虑以下简单示例:
<head>
<script language="javascript" type="text/javascript">
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.buttonClicked;
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
</script>
</head>
<body>
<input type="button" id="btn1" value="Click me" />
<script language="javascript" type="text/javascript">
var btn1counter = new ClickCounter('btn1');
</script>
</body>
事件处理程序 buttonClicked 被调用,但 _clickCount 成员不可访问,或者this指向其他对象。
关于这类问题的任何好的提示/文章/资源?