简体   繁体   English

JavaScript链接两个对象

[英]JavaScript linking two objects

What is a memory efficient way to link two objects? 连接两个对象的内存有效方式是什么? If you store objects using two arrays with corresponding index values the object won't be released from memory. 如果使用两个具有相应索引值的数组存储对象,则不会从内存中释放该对象。

The implementation should look like the following. 该实现应如下所示。

var obj ={};
var linkedobj = getLinkedObject(obj);
var obj2 ={}
var linkedobj2 = getLinkedObject(obj2);            

Objects are general containers 对象是通用容器

If all you want to do is associate one object with another one, then why not have them point to one another? 如果您要做的只是将一个对象与另一个对象相关联,那为什么不让它们指向另一个对象呢?

var obj = {};
var obj2 = {};

obj.linkedObject = obj2;
obj2.linkedObject = obj;

This would a normal thing to do, and doesn't have bad implications on memory. 这是正常的事情,不会对内存造成不良影响。

Releasing memory 释放内存

If you are asking about holding a table full of object references, you are correct that the object will not disappear until all of the live references to it are gone. 如果您要保存一个充满对象引用的表,那是正确的,直到对象的所有活动引用都消失了,该对象才会消失。 Javascript has a garbage collector, and as long as your table or array has a good reference, it will be backed by memory for you. Javascript具有垃圾回收器,只要您的表或数组具有良好的引用,它就会为您提供内存支持。 If you give an object to a table and then want it to be deleted from memory entirely, you can simply remove it from your table also. 如果将对象提供给表,然后希望将其完全从内存中删除,则也可以将其从表中删除。 You could also just remove the table, assuming it doesn't need to hold anything else. 您也可以删除该表,假设它不需要容纳其他任何东西。

If you are determined to have a getLinkedObject function return an object for another object, you can still allow the objects to each hold the associate reference. 如果确定要让getLinkedObject函数返回另一个对象的对象,则仍然可以允许这些对象各自保存关联引用。

function getLinkedObject(anObject) {
    return anObject.linkedObject;
}

This would probably be accompanied by a counterpart: 这可能会伴随一个同行:

function linkObjects(anObject, anotherObject) {
    anObject.linkedObject = anotherObject;
    anotherObject.linkedObject = anObject;
}

Doing this allows you to worry a little less about memory management, which in Javascript (a high-level, dynamic environment with a garbage collector) is typically appropriate. 这样做使您不必担心内存管理,这在Javascript(带有垃圾收集器的高级动态环境)中通常是合适的。

Unless you use keparo's answer, which from your follow-up comment sounds like not an option, what you're asking for is basically impossible. 除非您使用keparo的答案(在后续评论中听起来像是没有选择),否则您基本上不可能提出要求。 Because, since you can't augment the original object, you need some method of storing a reference to it. 因为,因为您不能扩充原始对象,所以需要某种存储对它的引用的方法。 But (since JavaScript has no concept of weak references) this will always prevent it from being garbage collected, contradicting your requirements statement. 但是(由于JavaScript没有弱引用的概念),这将始终防止对其进行垃圾回收,这与您的需求声明相矛盾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM