Javascript 如何正确地与对象内的父函数/对象交互
我有一个名为Application的主对象,它将存储与这个特定脚本相关的所有函数。 该对象中有一些不同的函数,例如,start和pause,它们与子对象交互 当从Application对象的子对象调用这些函数时,甚至更深一层,我必须直接引用Application.function。它会变得很笨重。如果我需要与子数据this.Game.instance.sessionId交互,这些函数中的情况也是一样的。它注定要失败,如果我在未来随着需求的增长添加更多的对象会怎么样?仅仅与另一个子/父对象交互就会变得非常混乱,更不用说冗长了 示例代码:Javascript 如何正确地与对象内的父函数/对象交互,javascript,object,coding-style,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?
}
}
}
};
请原谅这愚蠢的代码,我只是想说明我的问题
如何以最恰当、最干净的方式构造此对象,或者更确切地说是重建此对象?对象之间没有固有的永久关系,而这些关系恰好是以您描述的方式定义的。换句话说,为属性游戏定义的对象本质上与应用程序对象无关,实例也与游戏无关。如果您希望它是,您必须显式地给它一个与之相关的属性
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();
现场演示:
为了更舒适,您可以使用以下示例:
gameobj = App.getGameObj();
gameobj.parentF();