javascript - 停止对象的 js 间隔

标签 javascript javascript-objects intervals

谁能告诉我为什么这段代码不能按我期望的方式工作?

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/

相关文章:

javascript - Bootstrap 3 下拉动画/缓动

javascript - Express Router 对一个 url 的 post 方法返回 404

javascript - 检查一个值是否是 JavaScript 中的对象

c++ - 有没有办法在 boost::icl::interval_map 中获取间隔数?

sql - 将两个表从第一个日期开始连接到第二个日期范围内

javascript - 当工具提示出现时,顶部的 Chart.JS 值消失

javascript - 如何禁用导航覆盖中的主体滚动并在主体中启用它?

javascript - 我添加了 javascript 按钮但不起作用

创建对象后的 JavaScript 函数

android - 在自定义 ListView 中更新 TextView