【发布时间】:2014-03-16 20:22:47
【问题描述】:
我正在创建一个 melonJS 游戏。
在我的玩家实体 - game.PlayerEntity = me.ObjectEntity.extend({ 中,它的更新函数会检查碰撞:
game.PlayerEntity = me.ObjectEntity.extend({
var collision = me.game.collide(this);
if (collision) {
if (collision.obj.type == me.game.ACTION_OBJECT) {
console.log("NPCname: " + game.NPCEntity.init); //get settings from NPCEntity
}
}
然后在我的NPC实体对象game.NPCEntity = me.ObjectEntity.extend ({中,我想将settings.name返回给上面的PlayerEntity。为此,我创建了一个闭包 returnSettings()。
1) console.log(settings.name) 按预期输出“Lee”
2) return settings.name 输出“未定义”
这是为什么?
game.NPCEntity = me.ObjectEntity.extend ({
init : function(x, y, settings) {
settings.image = "wheelie_right";
settings.spritewidth = 64;
settings.name = "Lee";
this.parent(x, y, settings);
this.collidable = true;
this.type = me.game.ACTION_OBJECT;
console.log(settings.name); //works
console.log("returning... " + returnSettings()); //works
//closure to return settings values externally
function returnSettings () {
return settings.name; //returns undefined when called by PlayerEntity above.
}
},
谢谢!
【问题讨论】:
-
你在调用returnSettings函数吗?在上面你有
console.log("NPCname: " + game.NPCEntity.returnSettings)。而且不需要函数,直接this.settings = settings访问属性即可。 -
我正在尝试从 game.PlayerEntities 对象访问 game.NPCEntity 的
settings。 -
您的第一个示例是语法错误,您将函数与对象文字混合在一起。
-
现在你至少在调用它,
returnSettings闭包不是NPCEntity对象的属性,而是init函数的返回值! -
@Bergi 是的,我明白了。我固定在上面。仍然收到
Cannot call method 'returnSettings' of undefined
标签: javascript closures melonjs