Accessing an object's parent (or instance?) gi

2019-09-20 06:28发布

问题:

This question already has an answer here:

  • Javascript objects: get parent [duplicate] 12 answers

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.