溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

NodeJS中怎么實(shí)現(xiàn)循環(huán)引用

發(fā)布時(shí)間:2021-07-21 11:08:49 來源:億速云 閱讀:147 作者:Leah 欄目:web開發(fā)

這篇文章將為大家詳細(xì)講解有關(guān)NodeJS中怎么實(shí)現(xiàn)循環(huán)引用,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

場景復(fù)現(xiàn)

出現(xiàn)問題場景比較簡單,一共四個(gè)類:

  • 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";
 }

}

這個(gè)時(shí)候我們?nèi)?gòu)造一個(gè)Child類:

import {Child} from "./child";

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

就會直接報(bào)錯(cuò)了:

class Child_2 extends parent_1.Parent {
^

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

#尋找原因

說的是這個(gè)父類是一個(gè)undefined,很明顯就是沒有初始化。

一開始我覺得很奇怪,明明在child_2這個(gè)文件里已經(jīng)import了parent,為什么會是undefined呢?后來debug查了一下代碼的堆棧,恍然大悟:

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

很明顯這里存在著一個(gè)循環(huán)引用,當(dāng)我們在加載child_2.ts這個(gè)文件的時(shí)候,parent.ts還處在未加載完的狀態(tài)。

我們可以去 官網(wǎng)看一下node中是如何處理循環(huán)引用的 。

通過官網(wǎng)我們可以知道,對于這樣的循環(huán)引用,在child_2.ts加載parent.ts的時(shí)候,會去緩存中尋找,而由于parent.ts還未加載完成,所以緩存中會是一個(gè)空對象了,官網(wǎng)中用的語句是 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的時(shí)候,就會先export對象,然后再import所需要的util.ts了。

關(guān)于NodeJS中怎么實(shí)現(xiàn)循環(huán)引用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI