在 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');
服务器.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
关于node.js - 检查nodejs中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37837695/