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

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

提交回复
热议问题