Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does isPrototypeOf() return false?

Tags:

javascript

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
like image 315
Gautam Avatar asked Apr 24 '19 01:04

Gautam


2 Answers

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
like image 109
Kaiido Avatar answered Oct 14 '22 04:10

Kaiido


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
like image 38
David Klinge Avatar answered Oct 14 '22 05:10

David Klinge