温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

NodeJS中怎么实现循环引用

发布时间:2021-07-21 11:08:49 来源:亿速云 阅读:146 作者:Leah 栏目:web开发

这篇文章将为大家详细讲解有关NodeJS中怎么实现循环引用,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

场景复现

出现问题场景比较简单,一共四个类:

  • parent.ts

  • child.ts

  • child_2.ts

  • util.ts

export abstract class Parent {

 abstract hello(): string;
}
import {Parent} from "./parent";

export class Child extends Parent {

 hello(): string {
  return "child";
 }

}
import {Child} from "./child";

export class Util {

 static useChildInSameCase(): string {
  let child: Child;
  return child.hello();
 }
}
import {Parent} from "./parent";

export class Child_2 extends Parent {

 hello(): string {
  return "child_2";
 }

}

这个时候我们去构造一个Child类:

import {Child} from "./child";

console.log(new Child().func());

就会直接报错了:

class Child_2 extends parent_1.Parent {
^

TypeError: Class extends value undefined is not a function or null

#寻找原因

说的是这个父类是一个undefined,很明显就是没有初始化。

一开始我觉得很奇怪,明明在child_2这个文件里已经import了parent,为什么会是undefined呢?后来debug查了一下代码的堆栈,恍然大悟:

入口文件->child.ts->parent.ts->util.ts->child_2.ts->parent.ts

很明显这里存在着一个循环引用,当我们在加载child_2.ts这个文件的时候,parent.ts还处在未加载完的状态。

我们可以去 官网看一下node中是如何处理循环引用的 。

通过官网我们可以知道,对于这样的循环引用,在child_2.ts加载parent.ts的时候,会去缓存中寻找,而由于parent.ts还未加载完成,所以缓存中会是一个空对象了,官网中用的语句是 an unfinished copy of the a.js 。

解决方案

知道原因之后,解决方案也就变得清晰了起来,一句话搞定,将parent.ts中的import语句放在后面:

export abstract class Parent {

  abstract hello(): string;

  func(): string {
    return Util.useChildInSameCase();
  }
}

import {Util} from "./util";

这样在加载parent.ts的时候,就会先export对象,然后再import所需要的util.ts了。

关于NodeJS中怎么实现循环引用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI