Javascript代码中的错误:范围问题还是逻辑问题?

Javascript代码中的错误:范围问题还是逻辑问题?,javascript,Javascript,我的蛇游戏在任何地方都会留下痕迹,而不是正确移动: (使用箭头键移动它) 我想知道这是否是一个范围问题 有关守则如下: 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 = th

我的蛇游戏在任何地方都会留下痕迹,而不是正确移动: (使用箭头键移动它)

我想知道这是否是一个范围问题

有关守则如下:

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);
}

for
循环中创建一个新变量,还是Javascript向外查看是否已经有一个变量?我认为是后者

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


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

此变量始终指向其定义的上下文

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使用函数作用域而不是块作用域。

Javascript中没有块作用域。如果
temp
的两个用法都属于同一个函数,则它们是相同的变量。请注意,即使存在块作用域,也需要说
var temp=…
来获取新变量。
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