简体   繁体   中英

is object mutable in javascript? If yes, why the object of string is immutable then?

In javascript only object and arrays are mutable and remaining are primitive type which are immutable . However if we create an object of string,then it can't be mutated. why is that?

var a = new String("abc")
a.toUpperCase();
console.log(a) /*wont print "ABC" and prints an object with String:abc. Concludes 
that string object is immutable.*/

In general, yes, objects are mutable.

The reason that "string objects" - created with new String - are not mutable is that string objects result in objects which have an internal StringData property :

Set S.[[StringData]] to value.

That StringData is what is retrieved when the string object is coerced back to a primitive.

If the interpreter provided a way to change this StringData internal slot - then these sorts of objects would effectively be mutable. (Similarly, Set.add changes a Set's internal slot, and the same sort of mechanism exists for many other objects in JS - an exposed method changes values held in internal slots.)

But

a.toUpperCase();

alone wouldn't do anything - toUpperCase returns a new string. There are no methods (in standard implementations) that exist that can alter a string object's StringData internal slot - all you can do is create a new string object with a different StringData .

You could also strongly consider just not using string objects at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM