javascript - Javascript - 共享指针范式
问题描述
所以,我正在用 Javascript 编写一个 API。理想的要求包括它支持这样的结构:
- 有两个类:
class Core
和class Public
。两者都有成员id
。 - 不能有多个
Core
相同的实例id
,但每个实例必须有一个唯一的id
;但是,可能有任意数量的Public
实例具有相同的id
. Public
每个实例都有一个对类实例的单个引用,并Core
具有对应的值id
。Core
一旦Public
指向它的最后一个实例被垃圾收集,就应该对实例进行垃圾收集。- 因此,当一个新
Public
实例被创建并被赋予一个id
时,它会收集并将其引用分配给现有Core
实例(如果存在)或新实例(Core
如果不存在)。
并且最好(尽管不是绝对必要的):
- 当对
Core
实例的最后一个引用被删除时,将运行其上的方法(即析构函数)
此外,正如我在 ES6 中编写的那样,WeakMaps、WebAssembly 和任何其他现代 JS API 在答案中都是允许的。
这种结构在 Javascript 中是否可行?如果是这样,这种实现的结构是什么?或者,这完全超出了 Javascript 的能力范围吗?
解决方案
这种结构在 Javascript 中是否可行?
是的。但是你不能以任何方式拦截垃圾回收,如果对一个对象的所有引用都丢失了,它会默默地消失,没有人会注意到它。因此,如果你想注意到它,你必须明确地引起它:
class Reference {
constructor(to) {
this.to = to;
to.link();
}
free() {
this.to.unlink();
this.to = undefined;
}
}
class Referenceable {
constructor() {
this.count = 0;
}
link() { this.count++ }
unlink() {
if(!(--this.count)) {
// your last words
}
}
}
推荐阅读
- java - 如何开发、构建和部署多个基于 OSGi 的 Web 应用程序
- git - Git推送机密信息
- javascript - AppMaker 从服务器端返回值到客户端
- tensorflow - 使用 tf.keras 时带有大 numpy 数组的 from_tensor_slices()
- ubuntu-18.04 - SLURM srun 未在并行 Ubuntu 18 中运行 MPI 作业
- android - 在 Android 的 Repository 或 ViewModel 中使用共享的 Preference 值
- abap - 将命名空间 /FOO/ 的代码和数据类型复制到第二个 SAP 系统
- c# - Facebook 频道中缺少 From.Id 和 Conversation.Id 的 Bot 框架
- codeigniter - 有没有办法在codeigniter中以编程方式设置语言键值?
- time-series - 使用 BoxCox 转换后,如何返回原始数据?