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

标签 javascript object coding-style

我有一个名为 Application 的“主”对象,它将存储与该特定脚本相关的所有函数。 该对象中有一些不同的函数,例如 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;

关于javascript - 如何与对象内的父函数/对象正确交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9243746/

相关文章:

javascript - 在 Mapbox 中使用 map.addLayer 添加编辑多边形

javascript - 获取javascript对象中的最后一项

c# - 代码格式样式 - 哪一种更可取

javascript - React Hooks 在声明之前从 useState 访问状态

javascript - iOS VoiceOver 滚动、内部 div、3 指向上/向下滑动

javascript - 添加到数组时新对象会被覆盖

javascript - 动态访问.map数组函数中的对象属性

java - DAO 和 Hibernate 类的标准命名

python - python中寻址属性的风格

javascript - 使用 Firebase 函数向 Android 应用发送通知