I can't figure out myself why foo.bar
in the example is undefined
, could you explain?
var foo = "foo";
foo.bar = "baz";
console.log(foo.bar); // undefined
Q2: How do I add references to properties and methods to the String
instance foo
?
Help is appreciated, thanks.
-- EDIT --
Note: the question is about a generic String instance, not the String global object. So using "classic" prototyping as someone suggested is not an option, because this way every String instance would have a property called bar
, while I want to augment only certain instances.
This is a duplicate of Why can't I add properties to a string object in javascript?.
Basically, you're creating a string, and this is a primitive type in javascript.
You cannot add properties to primitive types in javascript.