JavaScript中的var num = 30和var num = new Number(30)有什么区别?

Dra*_*zah 0 javascript syntax

似乎有很多不同的方法可以在JavaScript中执行相同的操作.在JavaScript中使用"new"关键字来表示数字并输入数字有什么不同吗?我认为没有区别:

var num = 30;

var num = new Number(30);
Run Code Online (Sandbox Code Playgroud)

字符串(和数组)也是如此:

var str = "hello";

var str = new String("hello");
Run Code Online (Sandbox Code Playgroud)

为什么有人会使用一种方法而不是另一种?它们对我来说似乎是一样的,而且无论如何它只是打字.

and*_*toi 5

第一个创建一个原语.另一个对象.

理论上存在差异,但在实践中没有.当需要成为对象时,JavaScript引擎会自动将基元打包到对象.

var myPrimitiveNumber = 42;
// calling .toFixed will 'box' the primitive into a number object,
// run the method and then 'unbox' it back to a primitive
console.log( myPrimitiveNumber.toFixed(2) );
Run Code Online (Sandbox Code Playgroud)

我发现的唯一用法是你想从构造函数返回一个原语.

function Foo() {
    return 42;
}

var foo = new Foo();
console.log(foo); // foo is instance of Foo

function Bar() {
    return new Number(42);
}

var bar = new Bar();
console.log(bar); // bar is instance of Number
Run Code Online (Sandbox Code Playgroud)