What is the difference between string primitives and String objects in JavaScript?

前端 未结 12 1658
孤街浪徒
孤街浪徒 2020-11-22 07:58

Taken from MDN

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., witho

12条回答
  •  無奈伤痛
    2020-11-22 08:32

    In Javascript, primitive data types such is string is a non-composite building block. This means that they are just values, nothing more: let a = "string value"; By default there is no built-in methods like toUpperCase, toLowerCase etc...

    But, if you try to write:

    console.log( a.toUpperCase() ); or console.log( a.toLowerCase() );
    

    This will not throw any error, instead they will work as they should.

    What happened ? Well, when you try to access a property of a string a Javascript coerces string to an object by new String(a); known as wrapper object.

    This process is linked to concept called function constructors in Javascript, where functions are used to create new objects.

    When you type new String('String value'); here String is function constructor, which takes an argument and creates an empty object inside the function scope, this empty object is assigned to this and in this case, String supplies all those known built in functions we mentioned before. and as soon as operation is completed, for example do uppercase operation, wrapper object is discarded.

    To prove that, let's do this:

    let justString = 'Hello From String Value';
    justString.addNewProperty = 'Added New Property';
    console.log( justString );
    

    Here output will be undefined. Why ? In this case Javascript creates wrapper String object, sets new property addNewProperty and discards the wrapper object immediately. this is why you get undefined. Pseudo code would be look like this:

    let justString = 'Hello From String Value';
    let wrapperObject = new String( justString );
    wrapperObject.addNewProperty = 'Added New Property'; //Do operation and discard
    

提交回复
热议问题