在给定子对象的情况下访问对象的父对象(或实例?) [英] Accessing an object's parent (or instance?) given a sub-object

查看:61
本文介绍了在给定子对象的情况下访问对象的父对象(或实例?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象变量 a,它有一个与之关联的数组 b.我正在将 b 传递给一个函数,并且需要检查 a 中的属性,即与其关联的对象.

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);

推荐答案

没有对象的父级的内置概念.因此,您的数组 a 根本没有引用您称之为其父级的内容.如果需要,您可以通过向 a 添加属性来向 a 添加一个.在您的行话中,除非您在 a 上设置指向 b 的属性,否则您无法从 a 获取 b>.

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.

但是,处理像您在 Javascript 中描述的情况的常用方法是只传递容器,这样您就拥有了容器,并且可以在需要时从容器中取出 a 或您可以同时传递容器和数组.

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.

没有父或容器概念的原因之一是因为 a 可以在许多其他对象中.当您有 {a: someArray} 时,someArray 数组实际上并不在"父对象中.相反,该对象中只有一个指向 someArray 的引用,并且可能有许多不同的对象指向 someArray.没有一个"容器.如果您想指定一个这样的容器,那么您可以在某处设置一个属性来指示您要涂油的容器,或者正如我之前建议的那样,您可以同时传递容器和对象,以便您调用的函数知道您使用的是哪个容器想用.

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.

这篇关于在给定子对象的情况下访问对象的父对象(或实例?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆