Lately I've been reading 'The Secrets of JavaScript Ninja' by John Resig and I've reached listing 4.10 i.e "Binding a Specific Context to a Function" in which the code is meant to print when the button is clicked. The author shows the code will run successfully only if an arrow function is used instead of the normal function expression. Why doesn't the code work fine with the function expression? and how does this keyword works?
Here is the code with the function expression:
function Button() {
this.clicked = false;
this.click = function() {
this.clicked = true;
if (button.clicked) {
"The button has been clicked"
};
};
}
var button = new Button();
var elem = document.getElementById("test");
elem.addEventListener("click", button.click);
<button id="test">Click Me!</button>
and here's the code with the arrow function (which works flawlessly):
function Button() {
this.clicked = false;
this.click = () => {
this.clicked = true;
if (button.clicked) {
console.log("The button has been clicked");
}
};
}
var button = new Button();
var elem = document.getElementById("test");
elem.addEventListener("click", button.click);
<button id="test">Click Me!</button>