Secrets of the JavaScript Ninja provides an interesting example:
HTML
<button id="test">Click me!</button>
JavaScript
var button = {
clicked: false,
click: function() {
this.clicked = true;
console.log("this:", this, "button.clicked?", button.clicked);
}
};
var elem = document.getElementById("test");
elem.addEventListener("click", button.click, false);
When testing this on http://jsfiddle.net/4hdQF/, the output is false
.
After changing the console.log
line to ...,
this.clicked?", this.clicked)", it works correctly now - see http://jsfiddle.net/YG8ST/.
The book suggests using bind
to improve the initial buggy application. But, is replacing button.clicked
with this.clicked
a valid solution? It appears so, as when the click
function is triggered, it references `this` to check if the current button was clicked.