欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于NodeJS中的循環(huán)引用詳解

 更新時間:2019年07月23日 08:26:29   作者:zjutkz  
這篇文章主要給大家介紹了關(guān)于NodeJS中的循環(huán)引用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用NodeJS具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

最近在用node的時候排查一個問題排查了半天,最終發(fā)現(xiàn)是循環(huán)引用導(dǎo)致的問題,故在此記錄一下。

場景復(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";
 }

}

這個時候我們?nèi)?gòu)造一個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這個文件里已經(jīng)import了parent,為什么會是undefined呢?后來debug查了一下代碼的堆棧,恍然大悟:

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

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

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

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

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論