这种不规则行为是由Javascript异步运行引起的吗?
Is this irregular behavior caused by Javascript running asynchronously?
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]。这有意义吗?
console.log
可以是异步的。看一看:
- JavaScript 控制台在分配变量之前打印变量的赋值?
- console.log() 异步还是同步?
所以,在行
console.log(head, newCoord);
您正在传递对head
的引用。在评估参照以打印其位置时,位置已经更改。相反,在另一行中:
console.log(head.pos, newCoord.pos);
您正在传递对当前存储在 head.pos
的对象的引用。然后,您可以为 head.pos
分配另一个值,但由 console.log
触发的进程(可能在此之后发生)仍将具有对原始对象的引用,因此它实际上将打印console.log
时间时的位置值。
相关文章:
- strongloop script.js run find in before delete方法:如何同步运行异步方法
- 如何测试运行 node-fluent-ffmpeg(异步模块)的自定义模块
- 在异步AJAX调用完成后,通过变量运行函数
- 如何在测试异步运行时使用 Sinon 沙箱
- javascript如何成为一种同步语言并在浏览器和node.js环境中异步运行
- 如何使用Grunt异步运行2同步任务
- 与promise串联运行异步函数
- 如何在 Node.js 中为非常大 (> 1GB) 文件的每一行运行异步函数
- 灯光开关加载所有数据或同步运行异步方法
- 并行运行异步任务
- 在PhantomJS中从Ant运行异步QUnit测试
- 在gump作业中运行异步操作
- 使用nodejs对两个任务运行异步
- 迭代数组在每个元素上运行异步任务
- 在express服务器启动时运行异步代码
- 从命令行运行异步代码,节点 js
- 用javascript编写一个可以按顺序运行异步函数的库
- 运行异步测试时出错
- 并行运行异步代码
- 运行异步函数N次,其中N取决于调用返回的内容