new Number()
和Number()
之间有什么区别?我知道new Number()
创建了一个Number
对象,而Number()
只是一个函数,但我何时应该调用哪个,为什么?
在相关的说明中,Mozilla说:
不要使用Boolean对象将非布尔值转换为布尔值。相反,使用布尔值作为执行此任务的函数。
x = Boolean(expression); // preferred x = new Boolean(expression); // don't use
为什么?我以为结果是一样的?
答案 0 :(得分:51)
Boolean(expression)
只会将表达式转换为 布尔原始值 ,而new Boolean(expression)
将创建 包装器对象 围绕转换后的布尔值。
可以看出差异:
// Note I'm using strict-equals
new Boolean("true") === true; // false
Boolean("true") === true; // true
还有这个(感谢@hobbs):
typeof new Boolean("true"); // "object"
typeof Boolean("true"); // "boolean"
注意:虽然包装器对象会在必要时自动转换为基元(反之亦然),但只有一种情况我可以想到你想要使用的地方{{1}或者,如果要将属性附加到单个值,则为基元的任何其他包装器。 E.g:
new Boolean
答案 1 :(得分:30)
new Number( x )
创建一个新的包装器对象。我认为没有合理的理由使用它。
Number( x )
将传递的参数转换为Number值。您可以使用它将一些变量强制转换为Number类型。然而,这完成了相同的工作:
+x
一般而言:
你不需要那些:
new Number()
new String()
new Boolean()
您可以使用它们进行投射:
Number( value )
String( value )
Boolean( value )
然而,有更简单的铸造解决方案:
+x // cast to Number
'' + x // cast to String
!!x // cast to Boolean
答案 2 :(得分:17)
始终值得咨询the spec;来自第15.7.1节:
当
Number
作为函数而不是构造函数调用时,它会执行类型转换。
同样,使用Boolean
作为函数(15.6.1):
当布尔值作为函数而不是构造函数调用时,它会执行类型转换。
...这意味着您参考了第9.2节(“ToBoolean”):
抽象操作ToBoolean根据表11将其参数转换为Boolean类型的值:
Undefined
=false
Null
=false
Boolean
=结果等于输入参数(无转换)。
Number
=如果参数为+ 0,-0或NaN,则结果为false;否则结果是真的。
String
=如果参数为空String(其长度为零),则结果为false;否则结果是真的。
Object
=true
new Boolean(value)
和Boolean(value)
之间的区别基本上是前者返回一个对象,但后者返回一个基元。这个很重要,因为对象很简单:
var b = new Boolean(false);
display(b); // Displays "false"
if (b) {
display("true"); // This is the path that gets taken, displaying "true"
}
else {
display("false"); // This path does NOT get taken
}
Live example ...而你几乎总是想要布尔人来测试它们。
答案 3 :(得分:0)
instanceof
的情况
const a = new Number('123'); // a === 123 is false
const b = Number('123'); // b === 123 is true
a instanceof Number; // is true
b instanceof Number; // is false
答案 4 :(得分:0)
// Type conversion to primitive value
const a = Number('42')
a === 42 // true
a.answer = 'You asked the wrong question'
a.answer // undefined
// Object
const b = new Number('42')
b === 42 // false
b.answer = 'Life, the Universe, and Everything'
b.valueOf() === 42 // true
b.answer // 'Life, the Universe, and Everything'