Javascript中字符串原语和字符串包装器对象之间的区别 [英] Difference between string primitive and string wrapper object in Javascript
问题描述
我对基元的包装对象感到非常困惑。例如,字符串基元和使用字符串包装器对象创建的字符串。
I'm very confused about what the wrapper objects for primitives. For example, a string primitive and a string created with the string wrapper object.
var a = "aaaa";
var b = new String("bbbb");
console.log(a.toUpperCase()); // AAAA
console.log(b.toUpperCase()); // BBBB
console.log(typeof a); // string
console.log(typeof b); // object
两者都可以访问 String.prototype
方法,似乎就像字符串文字一样。但是一个不是字符串,它是一个对象。 a
和 b
之间的实际区别是什么?为什么我要使用 new String()
创建一个字符串?
Both give access to String.prototype
methods, and seem to act just like a string literal. But one is not a string, it's an object. What is the practical difference between a
and b
? Why would I create a string using new String()
?
推荐答案
原始字符串不是对象。对象字符串是一个对象。
A primitive string is not an object. An object string is an object.
基本上,这意味着:
-
通过引用比较对象字符串,而不是它们包含的字符串
Object strings are compared by reference, not by the string they contain
"aaa" === "aaa"; // true
new String("aaa") === new String("aaa"); // false
对象字符串可以存储属性。
Object strings can store properties.
function addProperty(o) {
o.foo = 'bar'; // Set a property
return o.foo; // Retrieve the value
}
addProperty("aaa"); // undefined
addProperty(new String("aaa")); // "bar"
这篇关于Javascript中字符串原语和字符串包装器对象之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!