“新号码(...)”之间的区别是什么?和“数字(...)”在JavaScript? [英] What is the difference between "new Number(...)" and "Number(...)" in JavaScript?

查看:180
本文介绍了“新号码(...)”之间的区别是什么?和“数字(...)”在JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,其中一个将字符串转换为数字的可靠方法 Number 构造函数:

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 defaults to decimal

这个问题,我开始想知道—以上和之间有什么区别:

Inspired by this question, I started wondering — what is the difference between the above and:

var x =new Number('09');

数字肯定看起来更好,但似乎喜欢稍微不恰当地使用构造函数。没有,是否有任何副作用或使用它的任何差异?如果没有差异,为什么不,

Number certainly looks better, but it seems like a slightly inappropriate use of a constructor. Are there any side effects or any difference to using it without the new? If there is no difference, why not, and what is the purpose of new?

推荐答案

In第一种情况,您使用的是作为函数调用的数字构造函数 ,如规范中所述,只需执行类型转换,返回 Number 原语。

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第二种情况,您使用的是 Number 构造函数制作 数字对象

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.

这篇关于“新号码(...)”之间的区别是什么?和“数字(...)”在JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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