Is there a best-practice or common way in JavaScript to have class members as event handlers?
Consider the following simple example:
<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>
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?
EDIT almost 10 years later, with ES6, arrow functions and class properties
https://codepen.io/anon/pen/zaYvqq