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

前端 未结 2 1013
梦毁少年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

    The expression myVar.constructor just returns the value of the member "constructor". It's completely possible and legal for a given object to have a constructor which points to string (or anything else). For example

    function Apple() {}
    var x = new Apple();
    x.constructor = String
    if (x.constructor == String) {
      // True
    }
    

    Using the typeof operator though provides the information you're looking for

    if (typeof myVar == 'string') {
      // It's a string
    }
    
    0 讨论(0)
  • 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.

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