我的Javascript代码中的Bug:范围问题或逻辑问题

Bug in my Javascript Code: Scope Issue or Logic Issue?

本文关键字:问题 范围 Bug Javascript 代码 我的      更新时间:2023-09-26

我的蛇游戏到处留下痕迹,而不是正确移动:http://jaminweb.com/Snake.html(用方向键移动)

我想知道这是否可能是范围的问题。

相关代码为

var temp = this.body[0].clone();
// ....
this.body[0].translate(this.dx, this.dy);
for (var i = 1, j = this.body.length; i < j; ++i)
{
    var lastBB = temp.getBBox();
    var thisBB = this.body[i].getBBox();
    temp = this.body[i].clone();
    this.body[i].translate(lastBB.x-thisBB.x,lastBB.y-thisBB.y);
}

我在想,不,

temp = this.body[i].clone();

内部的for循环创建一个新的变量或Javascript看外面,看看是否已经有一个?我认为是后者。

temp = this.body[i].clone();创建一个新对象,因此您创建的新对象不会被翻译。

正如@MikeW在评论中指出的那样,JavaScript中没有for块作用域;作用域可以是全局的,也可以局限于一个函数。因此,代码中的tempfor循环内部和外部都是相同的变量。

this变量总是指向定义它的上下文。

function Constructor1
{
    this.x = 1;   // points to the objects instantiated by Constructor1
}
var a = new Constructor1;
a.x = 1;    // `this` points to a
var b = new Constructor1;
b.x = 1;    // `this` points to b
function func()
{
    return this;    // points to the calling function, returns itself
}
func() will return the function itself

Javascript使用函数作用域而不是块作用域