Why is 4 not an instance of Number?

前端 未结 5 1427
生来不讨喜
生来不讨喜 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:52

    As stated in Christoph's answer, string and number literals are not the same as String and Number objects. If you use any of the String or Number methods on the literal, say

    'a string literal'.length
    

    The literal is temporarily converted to an object, the method is invoked and the object is discarded.
    Literals have some distinct advantages over objects.

    //false, two different objects with the same value
    alert( new String('string') == new String('string') ); 
    
    //true, identical literals
    alert( 'string' == 'string' );
    

    Always use literals to avoid unexpected behaviour!
    You can use Number() and String() to typecast if you need to:

    //true
    alert( Number('5') === 5 )
    
    //false
    alert( '5' === 5 )
    

提交回复
热议问题