Class methods as event handlers in JavaScript?

前端 未结 4 1126
予麋鹿
予麋鹿 2020-11-29 00:59

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

Consider the following simple example:


            


        
4条回答
  •  感动是毒
    2020-11-29 02:01

    I don't know why Function.prototype.bind wasn't mentioned here yet. So I'll just leave this here ;)

    ClickCounter = function(buttonId) {
        this._clickCount = 0;
        document.getElementById(buttonId).onclick = this.buttonClicked.bind(this);
    }
    
    ClickCounter.prototype = {
        buttonClicked: function() {
            this._clickCount++;
            alert('the button was clicked ' + this._clickCount + ' times');
        }
    }
    

提交回复
热议问题