node.js - 检查nodejs中的继承

标签 node.js inheritance ecmascript-6

在 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/

相关文章:

node.js - 如何在heroku中显示node.js中的所有console.log?

ios - 对对象的引用返回 null(iOS 类继承)

javascript - 在用大括号定义其绑定(bind)后,如何访问该对象?

javascript - Khanacademy Javascript Canvas 默认参数错误

javascript - 模板字符串中的数字格式(Javascript - ES6)

node.js - 使用 nodemon 命令运行 npm 脚本

node.js - 使用npm install --production后遇到 "' vue-cli-service' is not recognized as an internal or external command”

javascript - console.log 未显示预期的对象属性

c# - 在派生类中重载基方法

java - 从抽象类派生时如何遵守equals()的契约