JavaScript - Why can't I add new attributes to a “string” object?

后端 未结 6 1383
误落风尘
误落风尘 2020-12-19 14:10

I\'ve experimented with JavaScript and noticed this strange thing:

var s = \"hello world!\";
s.x = 5;
console.log(s.x); //undefined

Every t

6条回答
  •  情深已故
    2020-12-19 15:14

    String objects are objects and can be expanded, but string literals are not string objects and can not be expanded.

    Example:

    var s = 'asdf';
    s.x = 42;
    alert(s.x); // shows "undefined"
    
    s = new String('asdf');
    s.x = 1337;
    alert(s.x); // shows "1337"
    

提交回复
热议问题