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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With