发布
社区首页 >问答首页 >JavaScript进度条不适用于OO JS代码,但适用于箭头函数?

JavaScript进度条不适用于OO JS代码,但适用于箭头函数?
EN

Stack Overflow用户
提问于 2019-03-07 15:41:04
回答 1查看 40关注 0票数 0

这是我发布的这个问题的后续问题:JavaScript progress bar does not work with oo js code

除了上面的解决方案之外,我尝试使用箭头函数重写OO脚本,代码是:

代码语言:javascript
代码运行次数:0
复制
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 + '%';
    }
  };
}
代码语言:javascript
代码运行次数:0
复制
#myProgress {
  width: 100%;
  background-color: grey;
}

#myBar {
  width: 1%;
  height: 30px;
  background-color: black;
}
代码语言:javascript
代码运行次数:0
复制
<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>

而且它不需要使用.bind() (正如最初的帖子中所说的)。为什么?这个箭头函数用例和上一篇文章中的构造函数/原型用例有什么不同?

EN

回答 1

Stack Overflow用户

发布于 2019-03-07 15:50:49

箭头函数没有自己的this、this继承和声明所在的函数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55038466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档