myVar.constructor --or— typeof myVar ---What is the difference?

前端 未结 2 1011
梦毁少年i
梦毁少年i 2021-01-23 00:42

What is the difference between...

if(myVar.constructor == String)

and

if(typeof myVar == \"string\")
2条回答
  •  囚心锁ツ
    2021-01-23 01:15

    typeof can be a little misleading. Note the following behavior:

    typeof fails on real String instances:

    typeof "snub" 
      // "string" -- as expected
    
    typeof new String("snub") 
      // "object" -- even if it's still the string you're after
    

    .constructor consistently yields the expected result:

    "snub".constructor == String 
      // true -- as expected
    
    new String("snub").constructor == String 
      // true -- as expected
    

    All primitive values in JavaScript have a corresponding object wrapper. It's from where primitives find a prototype chain to inherit from.

    Values in JavaScript can be expressed in primitive form (specially inheriting from their respective objects), or directly in object form. It's possible some of your strings are converted into String instances along the way -- by a library perhaps -- and you won't even know it. String objects and primitives generally behave the same way. Except for with typeof, of course.

    Directly in object form -- even while the inner value may represent something that is a string, number, or otherwise -- typeof will respond with "object".

    .constructor is a more reliable way to identify an object's type, and is directly available to your primitive values (like all the rest of their inherited functionality) thanks to a language feature called Autoboxing.

提交回复
热议问题