是否有可能创建一个“弱参考”。在JavaScript中? [英] Is it possible to create a "weak reference" in javascript?

查看:161
本文介绍了是否有可能创建一个“弱参考”。在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中有没有办法为另一个对象创建弱引用? 以下是描述弱引用内容的维基页面。 这是另一篇用Java描述它们的文章。任何人都可以想到实现的方法在javascript中的这种行为?

Is there any way in javascript to create a "weak reference" to another object? Here is the wiki page describing what a weak reference is. Here is another article that describes them in Java. Can anyone think of a way to implement this behavior in javascript?

推荐答案

JavaScript中的weakrefs没有语言支持。您可以使用手动引用计数自行滚动,但不是特别顺利。你不能创建一个代理包装器对象,因为在JavaScript对象中永远不知道什么时候它们将被垃圾收集。

There is no language support for weakrefs in JavaScript. You can roll your own using manual reference counting, but not especially smoothly. You can't make a proxy wrapper object, because in JavaScript objects never know when they're about to be garbage-collected.

所以你的'弱引用'变成了使用add-reference和remove-reference方法在简单查找中使用key(例如整数),并且当不再有手动跟踪引用时,可以删除条目,将来对该键的查找返回null。

So your ‘weak reference’ becomes a key (eg. integer) in a simple lookup, with an add-reference and remove-reference method, and when there are no manually-tracked references anymore then entry can be deleted, leaving future lookups on that key to return null.

这不是一个真正的弱点,但它可以解决一些相同的问题。它通常在复杂的Web应用程序中完成,以防止在DOM节点或事件处理程序与与之关联的对象(如闭包)之间存在引用循环时,浏览器(通常是IE,尤其是旧版本)的内存泄漏。在这些情况下,甚至可能不需要完整的参考计数方案。

This is not really a weakref, but it can solve some of the same problems. It's typically done in complex web applications to prevent memory leakage from browsers (typically IE, especially older versions) when there is a reference loop between a DOM Node or event handler, and an object associated with it such as a closure. In these cases a full reference-counting scheme may not even be necessary.

这篇关于是否有可能创建一个“弱参考”。在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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