【问题标题】:Closure returning undefined unexpectedly闭包意外返回未定义
【发布时间】: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


【解决方案1】:
  1. 你不应该在这里使用闭包
  2. game.NPCEnity 不引用实例,而是构造函数。如果您在构造函数中设置this.settings = …,则您将在实例上创建一个属性。

您可以在处理冲突的update 函数中使用this keyword 访问实例,它确实指向player

引用教程:

// call by the engine when colliding with another object
// obj parameter corresponds to the other object (typically the player) touching this one
onCollision: function(res, obj) {…}

这意味着您可以通过该事件处理程序中的obj.settings 访问敌人设置。


如果您没有使用该处理程序,而是调用了collide method,那么我看到该函数的返回值有一个.obj 属性,这可能是碰撞目标:

if (collision) {
    if (collision.obj.type == me.game.ACTION_OBJECT) {
        console.log("NPCname: " + collision.obj.settings.name); //get settings from NPCEntity
    }
}

【讨论】:

    【解决方案2】:

    显然您可以在定义之前调用该函数,因为它是以 function name(){} 方式定义的,而不是表达式:https://stackoverflow.com/a/261682/880114

    但我看不到你从哪里返回该函数以从其他地方调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-21
      • 2012-09-18
      • 1970-01-01
      • 2023-02-26
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多