Индикатор выполнения JavaScript не работает с кодом OO JS - PullRequest
1 голос
/ 06 марта 2019

Я пытаюсь переписать это демо ОО способом: https://www.w3schools.com/howto/howto_js_progressbar.asp Это мой код:

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, 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>

Проблема в том, что, как только я нажимаю кнопку, панель не прогрессирует, как я ожидаю, вместо этого в консоли отображается Uncaught TypeError: Cannot read property 'style' of undefined at frame. Что здесь не так? Кажется, что this.width не передается от Progressbar() к его прототипу.

1 Ответ

3 голосов
/ 06 марта 2019

Ваша ошибка означает, что вы пытались прочитать что-то вроде этого:

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...