gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:00:34 25 4
gpt4 key购买 nike

我有一个名为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com