Gautam
Gautam

Reputation: 825

Why does isPrototypeOf() return false?

I have the below constructors and SubType prototype pointing to an instance of SuperType. When I do x.isPrototypeOf(SubType.prototype) it returns false. I am confused as I have explicitly set x as a prototype for SubType. Can someone tell me why this is happening?

function SuperType(){}
    
function SubType(){}

x = new SuperType();

SubType.prototype = x;
SubType.prototype.constructor = SubType;

console.log(x.isPrototypeOf(SubType)) // returns false
console.log(SuperType.prototype.isPrototypeOf(SubType.prototype)) // returns true

Upvotes: 7

Views: 588

Answers (3)

Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

I think that this is misunderstanding of prototype and __proto__ properties.

Lets modify example above a little

function SuperType(){}

function SubType(){}

x = new SuperType();

SubType.prototype = x;
console.log(x.isPrototypeOf(SubType)) // returns false.

// Now most interesting piece
SubType.__proto__ = x;
console.log(x.isPrototypeOf(SubType)) // Now true.

Demo

In place of SubType.__proto__ = x we may use Object.setPrototypeOf(SubType, x) which will yeilds the same result

The trik is __proto__ holds real object which is prototype. prototype is used only in constructor fucntions for defining prototype for constructed objects. (See here)

So if we again modify first example

function SuperType(){}

function SubType(){}

x = new SuperType();

SubType.prototype = x;

console.log(x.isPrototypeOf(SubType)) // returns false

var x2 = new SubType();
console.log(x.isPrototypeOf(x2)) // returns true

Demo

Upvotes: 0

David Klinge
David Klinge

Reputation: 360

It helps to add properties to the objects to see what's happening. I fixed a little of your code. You can run this in the console:

function SuperType(foo){ this.foo = foo };
function SubType(bar){ this.bar = bar };

var x = new SubType("bar");

SuperType.prototype = x;
SuperType.prototype.constructor = SubType;

Now, you asked x.isPrototypeOf(SuperType) and it returns false, because x is not a property of the class SuperType. But when you instantiate a SuperType, x is a property of that new object:

var y = new SuperType("foo");
console.log(x.isPrototypeOf(y)) // returns true

In your example that is true, SubType.prototype is a prototype of SuperType.prototype and returns true.

console.log(SubType.prototype.isPrototypeOf(SuperType.prototype)) // returns true

Upvotes: 2

Kaiido
Kaiido

Reputation: 136638

SubType is a function. What you probably want to check is if an instance of SubType would inherit from x:

function SuperType(){}
    
function SubType(){}

x = new SuperType();

SubType.prototype = x;
SubType.prototype.constructor = SubType;

const instance = new SubType();
console.log(x.isPrototypeOf(instance)) // returns true
console.log(SuperType.prototype.isPrototypeOf(SubType.prototype)) // returns true

Upvotes: 6

Related Questions