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

后端 未结 6 1382
误落风尘
误落风尘 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:11

    Skilldrick’s answer explains why it doesn’t work and therefore answers your question.

    As a side note, it is possible to do this:

    var s = {
      toString: function() { return "hello world!"; }
    };
    s.x = 5;
    console.log(s.x); // 5
    console.log('result: ' + s); // "result: hello world!";
    console.log(String(s)); // "hello world!";
    

提交回复
热议问题