Difference between string primitive and string wrapper object in Javascript [duplicate]

♀尐吖头ヾ 提交于 2019-12-08 09:12:30

问题


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

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()?


回答1:


A primitive string is not an object. An object string is an object.

Basically, that means:

  • 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"
    


来源:https://stackoverflow.com/questions/30984463/difference-between-string-primitive-and-string-wrapper-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!