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

问题描述

新号码()号码()之间有什么区别?我得到 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:

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

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

10-28 23:03