在nodejs中检查继承的最佳方法是什么?
我试图在另一个继承该模块类的模块的类的实例中使用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();
解决方法
这是因为装载问题!当您加载C类时,它会请求A类并在定义C之前运行它.
我自己尝试过,如果我按照你提到的那样做并要求两个类,第二个比较失败了.
然而,这个工作:
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
为了更好地理解发生的事情,我创建了这个例子
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 will compare something true false