Object and String prototypes are not prototypes of defined strings?

后端 未结 3 869
遇见更好的自我
遇见更好的自我 2021-01-20 01:45

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?

         


        
3条回答
  •  天涯浪人
    2021-01-20 02:05

    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

提交回复
热议问题