0

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>
Karan Dhir
  • 645
  • 1
  • 5
  • 21
  • 2
    When using the arrow expression, `this` maintains its current scope, while when using the regular function expression `this` changes its scope to refer to the scope inside of the function. – bamtheboozle Jul 17 '17 at 09:06
  • 1
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – abhishekkannojia Jul 17 '17 at 09:07
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Serge K. Jul 17 '17 at 09:07

1 Answers1

0

You can run the following code.

function Button1() {
  this.clicked = false;
  this.click = function() {
    this.clicked = true;
 console.log('bt1',this);
    if (button1.clicked) {
      console.log("The button has been clicked 1"); 
    };
  };
}
function Button2() {
  this.clicked = false;
  this.click = () => {
    this.clicked = true;
 console.log('bt2',this);
    if (button2.clicked) {
      console.log("The button has been clicked 2");
    }
  };
}

var button1 = new Button1();
var button2 = new Button2();
var elem = document.getElementById("test");
elem.addEventListener("click", button1.click);
elem.addEventListener("click", button2.click);
<button id="test">Click Me!</button>

'this' is only a HTML in normal function.

if yuo use 'button1.click.bind(button1)', will run successfully.

Whj
  • 680
  • 2
  • 5
  • 13