简体   繁体   中英

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

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

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

Every type of variable in JavaScript is inherited from object. So it should be possible to add new attributes to every object.

Did I misunderstand something wrong?

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!

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"

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!";

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.

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, eg a String object wraps around a string primitive.
All primitives are immutable .

Try to do this:

var s = "hello world!";
s.prototype.x = 5;
console.log(s.x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM