JavaScript进度栏不适用于OO JS代码

时间:2019-03-06 16:38:20

标签: javascript html css oop

我正在尝试以OO方式重写此演示: 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 个答案:

答案 0 :(得分:3)

您的错误意味着您尝试读取以下内容:

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>