Why does instanceof return false for some literals?

前端 未结 10 1147
耶瑟儿~
耶瑟儿~ 2020-11-22 13:13
"foo" instanceof String //=> false
"foo" instanceof Object //=> false

true instanceof Boolean //=> false
true instanceof Object //=>         


        
10条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 13:41

    For me the confusion caused by

    "str".__proto__ // #1
    => String
    

    So "str" istanceof String should return true because how istanceof works as below:

    "str".__proto__ == String.prototype // #2
    => true
    

    Results of expression #1 and #2 conflict each other, so there should be one of them wrong.

    #1 is wrong

    I figure out that it caused by the __proto__ is non standard property, so use the standard one:Object.getPrototypeOf

    Object.getPrototypeOf("str") // #3
    => TypeError: Object.getPrototypeOf called on non-object
    

    Now there's no confusion between expression #2 and #3

提交回复
热议问题