检查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();
这是因为加载问题! 加载类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
- TypeError:超级expression式必须为null或者一个函数,而不是用Babeljs定义的
- Javascript可写描述符是否阻止实例的更改?
- 节点js原型对象'self'var不存储正确的callback上下文
- 如何扩展更多的“期望”functionfrisby.js?
- Javascriptinheritance对象覆盖其他inheritance对象
- NodeJS对象的inheritance
- Node.js / Express.js – 如何重写/拦截res.render函数?
- inheritance函数如何在Node.js中工作?
- 为什么NodeJS util.inherits函数中的“super_”属性添加到构造函数中?