如何与对象内的父函数/对象正确交互

时间:2012-02-11 20:22:12

标签: javascript object coding-style

我有一个名为Application的“主”对象,它将存储与此特定脚本相关的所有函数。 该对象中有一些不同的函数,例如start()pause(),它们与子对象进行交互。

从子对象(Application对象,甚至更深层)调用这些函数时,我必须直接引用Application.function()。哪个可以非常 clutty 。如果我需要与子数据this.Game.instance.sessionId进行交互,那么这些函数中的情况也是如此。它失败了,如果随着我的需求增长,我将来会添加更多的对象怎么办?它会变得非常混乱,更不用说冗长了,只是为了与另一个子/父对象进行交互。

示例代码:

    var Application = {     
       //Start the whole application
       start: function() {
          doSomething(this.Game.instance) //do something with the game instance object
       },

       pause: function() {
          //pause the current sessionId
          interactWithMyServer(this.Game.instance.sessionId); //clutty
       }

       Game: {  
          //redraw the game to reflect changes
          redraw: function() {
             someDrawFunction(this.instance); //draw the instance
          },

          //Stores information about the game instance from the server, changes often
          //bad example with the pause, but just to get the idea of my example
          instance: {
             gameId: 23,
             sessionId: 32,
             map: 32,

             //dummy function
             pause: function() {
             Application.pause(); //works, but I have to start with the "root" object, Application - how to avoid this?
             }
          }

      }             
   };

请原谅愚蠢的代码,只是试图表明我的问题。

如何以正确清洁的方式构建,或者更确切地说,重建?

2 个答案:

答案 0 :(得分:0)

在碰巧以您描述的方式定义的对象之间没有固有的永久关系。换句话说,为属性“Game”定义的对象与“Application”对象本质上没有关系,并且“实例”也与“Game”无关。如果你想要它,你必须明确地给它一个与之相关的属性。

  var Application = {
    // ...
    Game: {
      //redraw the game to reflect changes
      redraw: function() {
         someDrawFunction(this.instance); //draw the instance
      },

      //Stores information about the game instance from the server, changes often
      //bad example with the pause, but just to get the idea of my example
      instance: {
         gameId: 23,
         sessionId: 32,
         map: 32,
         app: null,

         //dummy function
         pause: function() {
           this.app.pause(); //works, but I have to start with the "root" object, Application - how to avoid this?
         }
      }

// ...

Application.Game.instance.app = Application;

答案 1 :(得分:0)

您可以通过定义一些闭包方法来传递对父级的引用:

var App= {


    aplicationFunction: function() {
        alert("Hello, yes this is application...");
    },

    app: this,

    getGameObj: function() {
        var _that = this;
        return {

            that: _that,

            parentF: function() {
                this.that.aplicationFunction();
            },
        };
    },
};

App.getGameObj().parentF();

现场演示:http://jsfiddle.net/vZDr2/

为了更加舒适,您可以使用它作为以下示例:

gameobj = App.getGameObj();
gameobj.parentF();