node.js – 检查nodejs中的继承

在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

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...