在一个循环中,我正在调用方法 bullet.fire();在这种方法中我有 this.i++,唯一的问题是 this.i 不会在每次迭代时更新,知道为什么吗?
function projectile(){
this.i = 20;
}
projectile.prototype.fire = function(){
this.i++;
//shows value of this.i in a div
document.getElementById("info").innerHTML = this.i;
}
在循环中
if(typeof(bullet) == "undefined"){
var bullet = new projectile(1);
}
bullet.fire();
最佳答案
确实火了!
您看不到进度有两个原因。首先,没有延迟,所以它是瞬间发生的。其次,javascript 在一个同步线程中工作。在线程完成之前,界面 (HTML) 不会刷新。
您可以使用一种 JavaScript 异步执行方法来中断线程。 setInterval
实例:
<div id="info"></div>
<script type="text/javascript">
function projectile(){
this.i = 20;
}
projectile.prototype.fire = function(){
this.i++;
//shows value of this.i in a div
document.getElementById("info").innerHTML = this.i;
}
var i = 3, bullet = new projectile(1), timer;
timer = setInterval(function () {
bullet.fire();
if (--i <= 0) clearInterval(timer);
}, 300);
</script>
关于javascript - 在方法调用中更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19693100/