Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if B is a "subclass" of A in Javascript/Node?

Given two classes like so:

function A(name) {
    this.name = name;
}

A.prototype.sayName = function() {
    console.log(this.name);
}

var B = require('some-class');

// B is subclass of A?

Is there a way to programmatically determine if B is a subclass of A?

Edit: In my case, B is a function and B.prototype extends A.prototype. B is not the return of new A(). B instanceof A does not seem to work.

like image 216
conradkleinespel Avatar asked Sep 22 '13 00:09

conradkleinespel


1 Answers

To check if B is a subclass of A (excluding the case where B === A):

B.prototype instanceof A

To check if B is a subclass of A (including the case where B === A):

B.prototype instanceof A || B === A

If you have an instance of B, the second test can be simplified to

b instanceof A // where b is an instance of B
like image 81
tom Avatar answered Oct 15 '22 22:10

tom