我正在用CraftyJS写一个小游戏。下面是我想写的内容:
Crafty.scene('MainMap', function() {
this.player = Crafty.e('Player');
this.player.move(5, 5);
this.game_objects = [this.player];
isOccupied: function(x, y) {
for (var i = 0; i < this.game_objects.length; i++) {
// ...
}
}
if (!this.isOccupied(5, 5)) { ... }
// ...
}不幸的是,这并不像预期的那样工作;它不是一个匿名对象,而是一个函数。我必须使用不同的语法,并传入我的对象,如下所示:
function isOccupied(x, y, game_objects) { ... }
// Same place as previous call to isOccupied
if (!isOccupied(x, y, this.gameObjects) { ... }我很清楚为什么必须将它声明为function isOccupied而不是isOccupied: function (因为它在函数中,而不是对象中),但是我不清楚this的作用域是什么。它不会传递到函数中。
有没有可能以某种方式将对象保持在某个非全局范围内,而不需要将它们传递到isOccupied中
发布于 2014-01-11 22:38:05
您可以将父作用域分配给另一个变量,这样它就可以在您的闭包中使用。像这样..。
Crafty.scene('MainMap', function() {
var self = this;
this.player = Crafty.e('Player');
this.player.move(5, 5);
this.game_objects = [this.player];
function isOccupied (x, y) {
for (var i = 0; i < self.game_objects.length; i++) {
// ...
}
}
}发布于 2014-01-11 22:39:42
Crafty场景中存在语法错误。
这部分中的冒号不应该在那里。在JavaScript中,冒号仅用于对象中。
// Wrong
isOccupied: function(x, y) {
for (var i = 0; i < this.game_objects.length; i++) {
// ...
}
}
// Right
function isOccupied(x, y) {
// ...
}在您的函数中,this引用全局对象(window)。
EDIT:要修复此问题,请使用Function.prototype.bind,如下所示:
function isOccupied(x, y) {
// ...
}.bind(this);发布于 2014-01-12 01:22:00
经过更多的研究,这似乎是一个带有this关键字的well-known issue。这个问题将在ECMAscript 5中修复。
总而言之:当您有多个级别的嵌套时,this关键字会变得混乱:
obj = {
speak: function() {
alert(this); // obj
inner = function() {
alert("inner: " + this); // window
};
}
};解决方法是通过将变量分配给this来使用作用域链
obj = {
speak: function() {
alert(this); // obj
var that = this;
inner = function() {
alert("inner: " + that); // obj instead of window
};
}
};对我来说不幸的是,CraftJS让我在函数中而不是对象中。要声明一个子函数,我仍然必须将其指定为function isOccupied
Crafty.scene('MainMap', function() {
self = this; // new
this.player = Crafty.e('Player');
this.player.move(5, 5);
this.game_objects = [this.player];
function isOccupied(x, y) { // game_objects no longer passed in
for (var i = 0; i < self.game_objects.length; i++) { // uses self
// ...
}
}
if (!this.isOccupied(5, 5)) { ... }
// ...
}https://stackoverflow.com/questions/21063489
复制相似问题