Ваша ошибка означает, что вы пытались прочитать что-то вроде этого:
undefined.style
Изучив код, вы можете увидеть, что ошибка происходит из функции Progressbar.frame
и имеет только одну строку, содержащую .style
.
Затем посмотрите, что перед ним: this.elem
... Это undefined
!
Основная проблема в том, что:
setInterval
множестваthis
к глобальному объекту при запуске предоставленной функции.
Вы можете избежать этого с помощью .bind()
:
document.getElementById("barButton").addEventListener("click", callMove);
function callMove() {
var bar1 = new ProgressBar();
bar1.move();
}
function ProgressBar() {
this.elem = document.getElementById("myBar"),
this.width = 1;
}
ProgressBar.prototype = {
constructor: ProgressBar,
move: function() {
this.id = setInterval(this.frame.bind(this), 300);
},
frame: function() {
if (this.width >= 100) {
clearInterval(this.id);
} else {
this.width++;
if (this.width >= 50) {
return;
}
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>