【发布时间】:2019-03-05 10:15:35
【问题描述】:
虽然我确实有一些 Python 编程经验,但我对 JavaScript 还是很陌生。 我的问题是,我似乎不理解 JS 中命名空间的概念,因为它似乎与 Python 中的不同。这是我的代码:
function snake(x, y) {
// x and y coordinate of square (topleft)
this.x = x;
this.y = y;
// reference to div object 'box2'
this.boxid = "#box";
this.box = document.getElementById(this.boxid);
// attempts to move the box by args
this.move = function (speedx, speedy) {
var m = 50;
// check if the box is within the container, moves if true
if ((this.x+(speedx*m))<=150 && (this.y+(speedy*m))<=150 &&
(this.y+(speedy*m))>=0 && (this.x+(speedx*m))>=0) {
this.x = this.x + speedx*m;
this.y = this.y + speedy*m;
}
}
// called every frame to update position of the box
this.update = function () {
$(this.boxid).css({top: this.y, left: this.x});
}
}
var snakeObj = new snake(100, 100);
var t = setInterval(s.update, 100);
当按下四个箭头键之一时,将使用正确的参数执行 move() 函数。
现在代码显示在那里的方式,JS 告诉我 update() 函数中的 x 和 y 值是“未定义的”。但是,只要我将它们从 this.x 和 this.y 更改为 snakeObj.x 和 snakeObj.y,以及将 this.boxid 更改为“#box”,一切都会完美运行。 我想了解为什么 update() 函数不能“访问”对象中的值,而 move() 函数却完全没问题。
为了澄清,工作代码如下所示:
function snake(x, y) {
// x and y coordinate of square (topleft)
this.x = x;
this.y = y;
// reference to div object 'box2'
this.boxid = "#box";
this.box = document.getElementById(this.boxid);
// attempts to move the box by args
this.move = function (speedx, speedy) {
var m = 50;
// check if the box is within the container, moves if true
if ((this.x+(speedx*m))<=150 && (this.y+(speedy*m))<=150 &&
(this.y+(speedy*m))>=0 && (this.x+(speedx*m))>=0) {
this.x = this.x + speedx*m;
this.y = this.y + speedy*m;
}
}
// called every frame to update position of the box
this.update = function () {
$("#box).css({top: snakeObj.y, left: snakeObj.x});
}
}
var snakeObj = new snake(100, 100);
var t = setInterval(s.update, 100);
【问题讨论】:
-
我假设
s.update我们应该是snakeObj.update()?问题不在于命名空间,也不在于当您将函数引用传递给 setInterval 时,this的值不是您认为的那样。您可以尝试使用以下方式显式绑定它:setInterval(snakeObj.update.bind(snakeObj), 100) -
与 Python 一样,
this的作用类似于隐式的self参数,但与 Python 不同的是,访问s.update不会创建绑定方法,而只是给出您仍需要传递的函数实例。
标签: javascript namespaces javascript-namespaces