类方法作为JavaScript中的事件处理程序? [英] Class methods as event handlers in JavaScript?

查看:111
本文介绍了类方法作为JavaScript中的事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有JavaScript的最佳实践或常见方法,让类成员作为事件处理程序吗?

Is there a best-practice or common way in JavaScript to have class members as event handlers?

考虑下面的简单示例:

<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 <

The event handler buttonClicked gets called, but the _clickCount member is inaccessible, or this points to some other object.

有关这类问题的任何好的提示/文章/资源?

Any good tips/articles/resources about this kind of problems?

推荐答案

ClickCounter = function(buttonId) {
    this._clickCount = 0;
    var that = this;
    document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };
}

ClickCounter.prototype = {
    buttonClicked: function() {
        this._clickCount++;
        alert('the button was clicked ' + this._clickCount + ' times');
    }
}

这篇关于类方法作为JavaScript中的事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆