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.
The difference can be seen with this:
// Note I'm using strict-equals
new Boolean("true") === true; // false
Boolean("true") === true; // true
And also with this (thanks @hobbs):
typeof new Boolean("true"); // "object"
typeof Boolean("true"); // "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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…