这源于 JavaScript 的一个怪癖:有原始字符串和对象字符串。原始字符串是您日常使用的字符串:
typeof "Hi! I'm a string!" // => "string"
但是,任何时候使用new
,都会创建一个对象而不是原始对象:
typeof new String("Hi! I'm a string!") // => "object"
每当您访问属性时,JavaScript 也会隐式地从原始字符串中创建一个对象字符串,因为只有对象才能具有属性:
var s = "Hi! I'm a string!";
s.property = 6; // s implicitly coerced to object string, property added
console.log(s.property); // => undefined
// property was added to the object string, but then the object string was
// discarded as s still contained the primitive string. then s was coerced again
// and the property was missing as it was only added to an object whose reference
// was immediately dropped.
你几乎从不想要一个对象字符串,因为它的怪癖(例如,一个空的对象字符串是真实的),所以new String
你几乎总是想要String
而不是使用。String
withoutnew
甚至可以将对象字符串转换回原始字符串:
typeof String(new String("Hi! I'm a string!")) // => "string"
我不知道这个问题是否出现在 TypeScript 中,但是原始/对象的区别,尤其是真实性问题在Boolean
. 例如:
var condition = new Boolean(false);
if(condition) { // always true; objects are always truthy
alert("The world is ending!");
}
简而言之,这是因为对象/原始的区别。您几乎总是需要可以选择的原语。