在我编写的代码中,一个对象具有另一个对象作为其属性之一。在第二个对象中,存在一个指向父对象的属性。现在,当我在 firebug 中查看该对象时,我可以无休止地探索这个自引用循环。
这是糟糕的编程吗?这样的设置会产生什么影响?有没有更好的方法来设置通过子对象访问父对象?
这是我所拥有的简化示例:
function Entity(){
this.subEntity = {parent:null};
}
function createEntity(){
var entity = new Entity();
entity.subEntity.parent = entity;
}
createEntity();
需要对象的父对象的目的是因为我正在使用一个库,该库创建了我已包装到自己的外部对象中的特定对象。库的方法指向它自己的对象,但有时我想指向我的外部对象以访问它的方法。谢谢。
根据 Kevin B 的说法,以下是对我的情况的更具体的了解:
var b2Listener = Box2D.Dynamics.b2ContactListener //library object
var listener = new b2Listener;
//Next I overwrite a method in order to gain control of it,
//which receives two arguments, one being a contact object which contains the two
//fixtures which collided, and the impulse is the force.
listener.PostSolve = function(contact, impulse){
conA = contact.GetFixtureA()
}
//But I have the fixtures wrapped in my own objects which have properties and methods
//outside the fixture which I would like to access within the PostSolve method.
希望有帮助。也许我应该编写一个返回父级的方法?但不知道如何在方法中引用它,除非我将父级设置为夹具的属性,这又回到了我的老问题。
最佳答案
window.window.window.window.window.window.window.window.......
反向引用实际上很有用。例如,<canvas>
的渲染上下文对象有一个 .canvas
属性指向回 Canvas 。虽然您确实可以自己跟踪 Canvas ,但它只会让引用内容变得更容易。
关于javascript - 不好的做法?对象内的对象指向父对象 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22968279/