检查nodejs中的inheritance

在nodejs中检查inheritance的最好方法是什么?

我想在一个inheritance这个模块的类的另一个模块的类的instanceof中使用instanceof

文件a.js

  class A{ } class B extends A{ } var b = new B(); b instanceof A ///this work global.c instanceof A //this doesn't work module.exports = A; 

文件c.js

 var A = require("./a"); class C extends A{ } global.c = new C(); 

       

网上收集的解决方案 "检查nodejs中的inheritance"

这是因为加载问题! 加载类C时,它请求类A,并在C被定义之前运行。

我自己尝试过,如果我按照你提到的要求做了这两个class,第二个比较失败了。

但是这个工作:

a.js

 class A{ callMeLaterAligator(){ console.log(b instanceof A) ///this work console.log(global.c instanceof A) //this now work } } class B extends A{ } var b = new B(); module.exports = A; 

c.js

 var A = require("./a"); class C extends A{ } global.c = new C(); 

主要方法

 require('services/c'); const a = require('services/a'); const aInst = new a(); aInst.callMeLaterAligator(); 

有输出

 true true 

为了更好地理解发生了什么,我创build了这个例子

a.js

 console.log('Hello, I am class A and I am not yet defined'); class A{ } class B extends A{ } var b = new B(); console.log('Hello, I am class A and I will compare something'); console.log(b instanceof A) ///this work console.log(global.c instanceof A) //this doesn't work module.exports = A; 

c.js

 console.log('Hello, I am class C and I am not yet defined'); var A = require("./a"); console.log('Hello, I am class C and I will now try to defined myself'); class C extends A{ } console.log('Hello, I am class C and I am defined'); global.c = new C(); console.log('Hello, I am class C and I am in global.c'); 

server.js

 require('services/c'); 

有这个输出

 Hello, I am class C and I am not yet defined Hello, I am class A and I am not yet defined Hello, I am class A and I will compare something true false Hello, I am class C and I will now try to defined myself Hello, I am class C and I am defined Hello, I am class C and I am in global.c 

如果您先将其更改为需要“a”,那么C根本就没有加载

server.js更改:

 require('services/a'); 

有这个输出

 Hello, I am class A and I am not yet defined Hello, I am class A and I will compare something true false