谁能告诉我为什么这段代码不能按我期望的方式工作?
function npc(name) {
this.name = name;
this.grid = [[0,9], [0,9]];
this.position = [0,0];
this.start = setInterval(function(){this.move() }, 1000);
this.stop = function(){clearInterval(this.start)};
this.move = function() {
this.position[0] = this.position[0] + Math.floor(Math.random() * 2);
this.position[1] = this.position[1] + Math.floor(Math.random() * 2);
if (this.position[0] > this.grid[0][1] || this.position[1] > this.grid[1[1]) {
this.position = [0,0];
};
console.log(this.name + " moved to " + this.position);
}
};
npc();
var bug = new npc("test-name");
bug.start();
bug.stop();
除非我先执行 npc(),否则 Bug.start() 不会运行,但即使如此,它也会将 undefined 记录为名称,并且不会停止使用 bug.stop()
抱歉,如果这是基本的东西,但我无法自己解决这个问题......
最佳答案
试试这个。
function npc(name) {
this.name = name;
this.grid = [[0,9], [0,9]];
this.position = [0,0];
var that=this;
this.start = setInterval(function(){that.move() }, 1000);
this.stop = function(){clearInterval(this.start)};
this.move = function() {
this.position[0] = this.position[0] + Math.floor(Math.random() * 2);
this.position[1] = this.position[1] + Math.floor(Math.random() * 2);
if (this.position[0] > this.grid[0][1] || this.position[1] > this.grid[1[1]]) {
this.position = [0,0];
};
console.log(this.name + " moved to " + this.position);
}
}
这会更改 setInterval 内的上下文。
就在这个函数定义之后 调用
var bug = new npc("test-name");
它显示了一些控制台 O/p,例如 测试名称移至 1,0 测试名称移至 2,0
关于javascript - 停止对象的 js 间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43309701/