Why does isPrototypeOf() return false?

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


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

Tags:

Javascript