Astolfo Hoscher Astolfo Hoscher - 5 months ago 8
Node.js Question

check inheritance in nodejs

how is the best way to check inheritance in nodejs

i'm trying to use instanceof in a instance of a class of another module that inherits a class for this module.

file 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;


file c.js

var A = require("./a");

class C extends A{

}

global.c = new C();

Answer

It is because of loading issue! When you load class C, it request class A and it is run before the C is defined.

I have tried it myself, if I did it as you mentioned and requested both classes, the second one comparision failed.

However this one works:

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();

The main method

require('services/c');
const a = require('services/a');
const aInst = new a();
aInst.callMeLaterAligator();

having output

true
true

To better understand whats going on, I have created this example

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');

Having this output

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

If you change it to require "a" first, then the C is not loaded at all

server.js change :

require('services/a');

Having this output

Hello, I am class A and I am not yet defined
Hello, I am class A and I will compare something
true
false
Comments