Accessing an object's parent (or instance?) given a sub-object [duplicate]

强颜欢笑 提交于 2019-12-13 10:25:30

问题


I have an object variable a, which has an array associated with it, b. I am passing b to a function and need to check properties in a, the object it's associated with.

How can I do this? Can I somehow use an event emitter?

function ObjectB (stuff) {
   this.a = new a();
}

function doSomething (s) {
//need to get b from a
}

var b = new ObjectB(info);
b.a.doSomething(5);

回答1:


There is no built-in notion of a parent of an object. So, your array a has no reference at all to what you call its parent. You could add one to a if you wanted by adding a property to a. In your lingo, you can't get b from a unless you set a property on a that points to b.

But, the usual way to handle a situation like you describe in Javascript is to either just pass the container so you then have the container and can get a out of the container when you need it or you can pass both the container and the array.

One of the reasons, there no notion of a parent or container is because a can be in lots of other objects. When you have {a: someArray}, the someArray array is not actually "in" the parent object. Instead, there's just a reference in that object that points to someArray and there could be many different objects that point to someArray. There is no "one" container. If you want to designate one such container, then you can set a property somewhere that indicates which container you want to anoint or as I suggested earlier, you can pass both the container and the object so the function you're calling knows which container you want it to use.

Can I somehow use an event emitter?

I don't see any way that an event emitter would be relevant to the question you asked. If you somehow think it is relevant, then we need to see your code to understand how it might be used here.



来源:https://stackoverflow.com/questions/46127198/accessing-an-objects-parent-or-instance-given-a-sub-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!