【发布时间】:2014-12-13 23:29:11
【问题描述】:
Snake.prototype.move = function() {
var head = this.head();
var newCoord = new Coord(head.pos);
console.log(head, newCoord);
console.log(head.pos, newCoord.pos);
this.segments.push(newCoord);
head.plus(this.dir);
if (this.growingCount > 0) {
this.growingCount -= 1;
} else {
this.segments.pop();
}
};
Coord() 构造函数和plus 函数:
var Coord = SnakeGame.Coord = function(pos) {
this.pos = pos;
};
Coord.prototype.plus = function(dir) {
if (dir === "U") {
this.pos[0] -= 1;
} else if (dir === "D") {
this.pos[0] += 1;
} else if (dir === "R") {
this.pos[1] += 1;
} else if (dir === "L") {
this.pos[1] -= 1;
}
};
head() 返回Snake 实例的segments 属性中的第一段。
我看到的问题是两个console.log 似乎显示不同的结果。第一行显示了 pos 值为 [3, 2] 的 Coord 对象(这不应该是这种情况,因为 head 尚未更新)。下一个 console 行,输出 [3, 3] 和 [3, 3] (应该是这种情况)。
发生了什么事?我觉得错误正盯着我看,我看不到它。
澄清:基本上head 和newCoord 在首次实例化时具有相同的位置(不变)。在head.plus(this.dir); 行之后,head 应该比newCoord 多一个位置。
该方法的一个执行应该有head.pos 是[3, 2] 和newCoord 有[3, 3]。下一次执行,head.pos 应该是 [3, 1],另一个 newCoord 应该是 [3, 2]。这有意义吗?
【问题讨论】:
-
代码中没有任何异步,除非你调用的函数是异步的。
-
所以我通过节点而不是通过浏览器运行它来检查它。节点正确显示它们,但是,我不明白为什么浏览器仍将 [3, 2] 显示为
Coord的值。 -
你能发布 Coord() 构造函数吗?