如何正确地与对象内部的父函数/对象交互
How to properly interact with parent functions/objects inside an object
我有一个名为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();
相关文章:
- 创建对象函数原型和代码是错误的
- JavaScript模块模式-如何在使用对象/函数之前激发构造函数/init函数
- 如何从onclick字符串中引用javascript对象函数
- 更改对象函数仅用于示例
- javascript和jQuery的嵌套对象函数中的变量范围
- 将对象函数传递给请求动画帧时丢失对象引用
- 对象函数返回函数而不是值
- 使用onclick调用属性对象函数
- javascript拉斐尔对象函数传递
- 如何从onClick事件调用对象函数
- 可以't获取具有“t”的对象变量;这个“;由setTimeout()函数调用的对象函数中的属性
- 对象没有't继承父对象函数
- 调用父对象函数
- "这个“;对象函数内部的引用
- 将变量添加到对象函数调用的末尾
- 传单错误:对象函数没有方法'createIcon'在LayerGroup中创建自定义图标标记时
- TypeError:对象函数Object(){〔本机代码〕}没有方法'方法'
- 挖空 - 单击绑定到对象函数 - 范围问题
- 类型错误: 对象函数...没有方法“打开”
- JavaScript 对象函数