新号码()与号码() [英] new Number() vs Number()

查看:97
本文介绍了新号码()与号码()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新号码()号码()之间有什么区别?我得到 new Number()创建一个 Number 对象和 Number()只是一个函数,但我应该何时调用哪个,为什么?

What is the difference between new Number() and Number()? I get that new Number() creates a Number object and Number() is just a function, but when should I call which, and why?

在相关的说明中,Mozilla说:

On a related note, Mozilla says:


不要使用Boolean对象将非布尔值转换为布尔值。相反,使用布尔值作为函数来执行此任务。

Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task.

x = Boolean(expression);     // preferred
x = new Boolean(expression); // don't use


为什么会这样?我认为结果是一样的?

Why is that? I thought the results were the same?

推荐答案

布尔(表达式)将表达式简单地转换为 布尔原始值 ,而 new Boolean(表达式)将创建转换后的布尔值周围的包装器对象

Boolean(expression) will simply convert the expression into a boolean primitive value, while new Boolean(expression) will create a wrapper object around the converted boolean value.

可以看出差异:

// Note I'm using strict-equals
new Boolean("true") === true; // false
Boolean("true") === true; // true

还有这个(感谢@hobbs):

And also with this (thanks @hobbs):

typeof new Boolean("true"); // "object"
typeof Boolean("true"); // "boolean"






注意: 虽然包装器对象会在必要时自动转换为原语(反之亦然),但只有一种情况我可以想到你想要使用的地方 new Boolean ,或原语的任何其他包装器 - 如果要将属性附加到单个值。例如:


Note: While the wrapper object will get converted to the primitive automatically when necessary (and vice versa), there is only one case I can think of where you would want to use new Boolean, or any of the other wrappers for primitives - if you want to attach properties to a single value. E.g:

var b = new Boolean(true);
b.relatedMessage = "this should be true initially";
alert(b.relatedMessage); // will work

var b = true;
b.relatedMessage = "this should be true initially";
alert(b.relatedMessage); // undefined

这篇关于新号码()与号码()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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