Why does instanceof return false for some literals?

前端 未结 10 805
耶瑟儿~
耶瑟儿~ 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:34

    You can use constructor property:

    'foo'.constructor == String // returns true
    true.constructor == Boolean // returns true
    
    0 讨论(0)
  • 2020-11-22 13:36
     typeof(text) === 'string' || text instanceof String; 
    

    you can use this, it will work for both case as

    1. var text="foo"; // typeof will work

    2. String text= new String("foo"); // instanceof will work

    0 讨论(0)
  • 2020-11-22 13:41

    This is defined in the ECMAScript specification Section 7.3.19 Step 3: If Type(O) is not Object, return false.

    In other word, if the Obj in Obj instanceof Callable is not an object, the instanceof will short-circuit to false directly.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题