JavaScript 中的 var num=30 和 var num=new Number(30) 有什么区别? [英] What is the difference between var num=30 and var num=new Number(30) in JavaScript?

查看:35
本文介绍了JavaScript 中的 var num=30 和 var num=new Number(30) 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中似乎有很多不同的方法可以做同样的事情.在 JavaScript 中使用new"关键字表示数字和只输入数字有什么区别吗?我看不出有什么区别:

It seems like there are so many different ways to do the same things in JavaScript. Is there any difference in using the "new" keyword in JavaScript for numbers and just entering a number? I see no difference between:

var num = 30;

var num = new Number(30);

字符串(和数组)也一样:

It's the same with strings (and arrays):

var str = "hello";

var str = new String("hello");

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

Why would someone use one method over the other? They seem the same to me, and it's just more typing anyway.

推荐答案

首先创建一个基元.另一个是一个对象.

The first creates a primitive. The other an object.

理论上有区别,但实际上没有区别.当需要成为对象时,JavaScript 引擎会自动装箱一个对象的原语.

In theory there is a difference but in practice none. The JavaScript engine automagicly boxes a primitive to an object when it needs to be an object.

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) );

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

The only usage I've found is if you want to return a primitive from a constructor function.

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

这篇关于JavaScript 中的 var num=30 和 var num=new Number(30) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆