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

后端 未结 6 1355
误落风尘
误落风尘 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 14:56

    A string in JavaScript isn't an instance of String. If you do new String('my string') then it will be. Otherwise it's a primitive, which is converted to a String object on the fly when you call methods on it. If you want to get the value of the string, you need to call toString(), as shown below:

    var s = new String("hello world!");
    s.x = 5;
    console.log(s.x); //5
    console.log(s); //[object Object]
    console.log(s.toString()); //hello world!
    
    0 讨论(0)
  • 2020-12-19 15:02

    Try to do this:

    var s = "hello world!";
    s.prototype.x = 5;
    console.log(s.x);
    
    0 讨论(0)
  • 2020-12-19 15:04

    Your s is a string literal, not a string object. String literals are handled differently:

    The reason you can't add properties or methods to a string literal is that when you try to access a literal's property or method, the Javascript interpreter temporarily copies the value of the string into a new object and then use that object's properties or methods. This means a String literal can only access a string's default properties or methods and those that have been added as prototypes.

    0 讨论(0)
  • 2020-12-19 15:10

    Primitives MDC docs are immutable.

    primitive, primitive value
    A data that is not an object and does not have any methods.
    JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined.
    With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive.
    All primitives are immutable.

    0 讨论(0)
  • 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!";
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题