0

This is a question following up this question posted by myself: JavaScript progress bar does not work with oo js code

Apart from the solution from the above post, I tried to re-write the OO script using arrow functions, the code is:

document.getElementById("barButton").addEventListener("click", callMove);

function callMove() {
  var bar1 = new ProgressBar();
  bar1.move();
}

function ProgressBar() {
  this.elem = document.getElementById("myBar"),
    this.width = 1;
  this.move = () => {
    this.id = setInterval(this.frame, 10);
  };
  this.frame = () => {
    if (this.width >= 100) {
      clearInterval(this.id);
    } else {
      this.width++;
      this.elem.style.width = this.width + '%';
    }
  };
}
#myProgress {
  width: 100%;
  background-color: grey;
}

#myBar {
  width: 1%;
  height: 30px;
  background-color: black;
}
<html>

<head>
  <title>
    This is a OO progress bar test.
  </title>
  <link rel="stylesheet" href="testOOProgressBar.css">
</head>

<body>
  <div id="myProgress">
    <div id="myBar"></div>
  </div>
  <br>
  <button id="barButton">Click Me</button>
  <script src="testOOProgressBar.js"></script>
</body>

</html>

And it works without using .bind() (as said in the original post). Why? What's the difference between this arrow function case and the constructor/prototype case in the previous post?

O.O
  • 1,389
  • 14
  • 29
one-hand-octopus
  • 2,229
  • 1
  • 17
  • 51

1 Answers1

0

The arrow function does not have its own this, its this inherits and the function where the declaration is located.

余俊浩
  • 26
  • 1