这是我发布的这个问题的后续问题:JavaScript progress bar does not work with oo js code
除了上面的解决方案之外,我尝试使用箭头函数重写OO脚本,代码是:
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>
而且它不需要使用.bind() (正如最初的帖子中所说的)。为什么?这个箭头函数用例和上一篇文章中的构造函数/原型用例有什么不同?
发布于 2019-03-07 15:50:49
箭头函数没有自己的this、this继承和声明所在的函数。
https://stackoverflow.com/questions/55038466
复制相似问题