LongInt
LongInt

Reputation: 1769

Check if instance has inherited function in prototype chain

If I have an inheritance method set up like this:

function A() {}


function B() {
    A.call(this,{});
}

B.prototype = Object.create(A);
B.prototype.constructor = B;

function C() {
    B.call(this, {});
}

C.prototype = Object.create(B);
C.prototype.constructor = C;


var a = new A();
var b = new B();
var c = new C();

Is it possible to confirm, that the instance c has A in it's prototype chain, or has the information been lost somewhere?

Upvotes: 1

Views: 178

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68635

No !!!. In your example

C.prototype = Object.create(C);
C.prototype.constructor = C;

You have a prototype of C instances set to C

If you change to C.prototype = Object.create(B);

you will see this

enter image description here

But this doesn't mean that your c is instanceof A. Why ? Because you have set the prototype to an Function not to an Object

If you will change your code to this, that its prototype will be an object

function A() {}


function B() {
    A.call(this,{});
}

B.prototype = Object.create(new A());
B.prototype.constructor = B;

function C() {
    B.call(this, {});
}

C.prototype = Object.create(new B());
C.prototype.constructor = C;


var a = new A();
var b = new B();
var c = new C();

In this case your c has A in it's prototype chain.

You can test it with c instanceof B and c instanceof A in the console

enter image description here

Upvotes: 1

Related Questions