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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With