Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 667
Van Coding Avatar asked Dec 22 '22 15:12

Van Coding


2 Answers

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!
like image 133
Skilldrick Avatar answered Feb 24 '23 08:02

Skilldrick


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"
like image 45
Guffa Avatar answered Feb 24 '23 07:02

Guffa