首页 > 解决方案 > Javascript - 共享指针范式

问题描述

所以,我正在用 Javascript 编写一个 API。理想的要求包括它支持这样的结构:

并且最好(尽管不是绝对必要的):

此外,正如我在 ES6 中编写的那样,WeakMaps、WebAssembly 和任何其他现代 JS API 在答案中都是允许的。

这种结构在 Javascript 中是否可行?如果是这样,这种实现的结构是什么?或者,这完全超出了 Javascript 的能力范围吗?

标签: javascriptecmascript-6garbage-collectionshared-ptr

解决方案


这种结构在 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
     }
   }
 }

推荐阅读