[英]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 .在javascript 中,只有对象和数组是可变的,其余的是不可变的原始类型。 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 : “字符串对象” - 用
new String
创建 - 不可变的原因是字符串对象导致具有内部StringData
属性的对象:
Set S.[[StringData]] to value.
将 S.[[StringData]] 设置为值。
That StringData
is what is retrieved when the string object is coerced back to a primitive. StringData
是当字符串对象被强制回原语时检索到的内容。
If the interpreter provided a way to change this StringData
internal slot - then these sorts of objects would effectively be mutable.如果解释器提供了一种方法来更改此
StringData
内部插槽 - 那么这些类型的对象实际上是可变的。 (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.) (同样,
Set.add
改变了一个 Set 的内部槽,同样的机制也存在于 JS 中的许多其他对象——一个暴露的方法改变了内部槽中的值。)
But但
a.toUpperCase();
alone wouldn't do anything - toUpperCase
returns a new string.单独不会做任何事情 -
toUpperCase
返回一个新字符串。 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
.不存在可以改变字符串对象的
StringData
内部槽的方法(在标准实现中) - 您所能做的就是使用不同的StringData
创建一个新的字符串对象。
You could also strongly consider just not using string objects at all.您也可以强烈考虑根本不使用字符串对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.