Javascript String Array-Like-Object behaviour

放肆的年华 提交于 2021-02-05 09:28:26

问题


When I run above code in Chrome dev console, I do not get any error. But when same code runs via js loaded on a webpage I receive this exception - Cannot create property 'name' on string 'some string'

Can someone please tell me why there is different behaviour in above 2 cases?


回答1:


Your webpage must be running that snippet of code in strict mode, in which assigning to properties of a string will throw an error:

'use strict';
const str = 'foo';
str.bar = 'bar';

In sloppy mode, it'll just fail silently:

const str = 'foo';
str.bar = 'bar';



回答2:


Strings are a value objects as in they have a value not a reference to an instance of an object, they cannot have properties set with a["name"] like reference objects can.

a[3] is the 4th character in the string, a[0] being the first.




回答3:


Let's see this case

const a = "a"
Object.isFrozen(a) // true
const b = new String("b")
Object.isFrozen(b) // false

From this section, we could see that String objects are not necessarily frozen. Only those string literals are frozen (I think it's because they are shared in a pool. If they are not frozen, you can create properties on one place to affect the code elsewhere) However, the explicitly constructed String objects are independent from the pool, thus not frozen.



来源:https://stackoverflow.com/questions/54564752/javascript-string-array-like-object-behaviour

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