I\'m trying to understand how JavaScript\'s prototype-based inheritance works. I was expecting the below outputs would evaluate as true
. Why is this?
Basically, isPrototypeOf
only works on objects, and string primitives are not objects, they are primitives.
If you were using the String
wrapper object, it would work (but don't do that!):
var myStr = new String("Sample");
console.log(String.prototype.isPrototypeOf(myStr)); // true
console.log(Object.prototype.isPrototypeOf(myStr)); // true
But the wrapper objects are generally bad practice, so don't use them.
Alternately, you could cast them to their object form when testing.
var myStr = "Sample";
console.log(String.prototype.isPrototypeOf(Object(myStr))); // true
console.log(Object.prototype.isPrototypeOf(Object(myStr))); // true