這篇文章將為大家詳細(xì)講解有關(guān)NodeJS中怎么實(shí)現(xiàn)循環(huán)引用,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
場景復(fù)現(xiàn)
出現(xiàn)問題場景比較簡單,一共四個類:
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"; } }
這個時(shí)候我們?nèi)?gòu)造一個Child類:
import {Child} from "./child"; console.log(new Child().func());
就會直接報(bào)錯了:
class Child_2 extends parent_1.Parent {
^TypeError: Class extends value undefined is not a function or null
#尋找原因
說的是這個父類是一個undefined,很明顯就是沒有初始化。
一開始我覺得很奇怪,明明在child_2這個文件里已經(jīng)import了parent,為什么會是undefined呢?后來debug查了一下代碼的堆棧,恍然大悟:
入口文件->child.ts->parent.ts->util.ts->child_2.ts->parent.ts
很明顯這里存在著一個循環(huán)引用,當(dāng)我們在加載child_2.ts這個文件的時(shí)候,parent.ts還處在未加載完的狀態(tài)。
我們可以去 官網(wǎng)看一下node中是如何處理循環(huán)引用的 。
通過官網(wǎng)我們可以知道,對于這樣的循環(huán)引用,在child_2.ts加載parent.ts的時(shí)候,會去緩存中尋找,而由于parent.ts還未加載完成,所以緩存中會是一個空對象了,官網(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é)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
文章名稱:NodeJS中怎么實(shí)現(xiàn)循環(huán)引用-創(chuàng)新互聯(lián)
分享路徑:http://www.rwnh.cn/article22/ppsjc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站營銷、網(wǎng)頁設(shè)計(jì)公司、App設(shè)計(jì)、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容