在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();
答案 0 :(得分:2)
这是因为加载问题!当您加载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 am not yet defined
Hello, I am class A and I will compare something
true
false