Why is 4 not an instance of Number?

前端 未结 5 1425
生来不讨喜
生来不讨喜 2020-11-27 03:03

Just curious:

  • 4 instanceof Number => false
  • new Number(4) instanceof Number => true?

Why is this? Same with strings:

5条回答
  •  执笔经年
    2020-11-27 03:45

    This is a nuance of Javascript which I've found catches some out. The instanceof of operator will always result in false if the LHS is not an object type.

    Note that new String('Hello World') does not result in a string type but is an object. The new operator always results in an object. I see this sort of thing:

    function fnX(value)
    {
         if (typeof value == 'string')
         {
              //Do stuff
         }
    }
    fnX(new String('Hello World'));
    

    The expectation is that "Do Stuff" will happen but it doesn't because the typeof the value is object.

提交回复
热议问题