What is the difference between “new Number(…)” and “Number(…)” in JavaScript?

后端 未结 4 712
青春惊慌失措
青春惊慌失措 2020-12-02 01:48

In Javascript, one of the reliable ways to convert a string to a number is the Number constructor:

var x = Number(\'09\'); // 9, because it defa         


        
4条回答
  •  执笔经年
    2020-12-02 02:33

    In the first case, you are using the Number Constructor Called as a Function, as described in the Specification, that will simply perform a type conversion, returning you a Number primitive.

    In the second case, you are using the Number Constructor to make a Number object:

    var x = Number('09');
    typeof x; // 'number'
    
    var x = new Number('09');
    typeof x; // 'object'
    
    Number('1') === new Number('1'); // false
    

    The difference may be subtle, but I think it's important to notice how wrapper objects act on primitive values.

提交回复
热议问题