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

How to properly interact with parent functions/objects inside an object

本文关键字:对象 函数 交互 内部 正确地      更新时间:2023-09-26

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

当从(Application对象的,甚至更深层次的)子对象调用这些函数时,我必须直接引用Application.function()。这会导致非常的混乱。如果我需要与子数据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?
             }
          }
      }             
   };

原谅这个愚蠢的代码,我只是想说明我的问题。

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

对象之间没有固有的永久关系,这些关系恰好是以您所描述的方式定义的。换言之,为属性"Game"定义的对象与"Application"对象没有本质上的关联,"instance"也与"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;

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

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();