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()
返回segments
个实例Snake
属性中的第一个段。
我看到的问题是两个console.log
似乎显示出不同的结果。第一行显示Coord
对象的pos
值为[3,2](由于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]。这有意义吗?
答案 0 :(得分:4)
console.log
可以是异步的。看看:
所以,在行
console.log(head, newCoord);
您正在传递对head
的引用。在评估参考以打印其位置时,位置已经改变。而在另一行中,改为:
console.log(head.pos, newCoord.pos);
您正在传递对当前存储在head.pos
的对象的引用。然后,您可以将另一个值分配给head.pos
,但由console.log
触发的过程(可能发生的时间晚于此)仍将具有对原始对象的引用,因此它实际上将打印该值的值在console.log
时间的位置。