views:

56

answers:

3

As far as I understand, every string is an object in Javascript. Still, it "does not work" as I expect it to be:

var a="abc";  //here we get a new string object
a.b = 123;    //I seem to declare a property "b" of that object
alert(a.b);   //alerts "undefined"

However, if I try to define a string in the "wrong way", everything works as expected

var a=new String("abc"); //
a.b = 123;
alert(a.b);    //alerts "123"

Why is that so?

+6  A: 

You may be interested in checking out the first part of this article:

Quoting:

There are two different types of Strings and the behave quite differently. A literal is created just by using quotes around your string. An object is created by implicit use of the new keyword. If you assign a string to a variable using the String keyword, without the new keyword the contents of the parenthesis will be cast as a string literal.

A string literal has access to all of a string's objects and methods because javascript will temporarily cast a string literal as a string object in order to run the desired method.

Where the two differ is their treatment of new properties and methods. Like all Javascript Objects you can assign properties and methods to any String object.

You can not add properties or methods to a string literal. They are ignored by the interpreter.

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.

Daniel Vassallo
Got it, thanks - "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." ;-)
naivists
A: 

This is also interesting reading... http://stackoverflow.com/questions/2018070/are-string-literals-objects-or-not

Upper Stage
+3  A: 

This happens because the property accessors, (. and []) convert the value ToObject.

Something equivalent to this happens behind the scenes:

var a="abc";
new Object(a).b = 123;  
alert(a.b); // undefined

Basically an object is created on the fly, by the property accessor, see the Step 5:

The production MemberExpression : MemberExpression [ Expression ] (or MemberExpression . Identifier) is evaluated as follows:

  1. Evaluate MemberExpression.

  2. Call GetValue(Result(1)).

  3. Evaluate Expression.

  4. Call GetValue(Result(3)).

  5. Call ToObject(Result(2)).

  6. Call ToString(Result(4)).

  7. Return a value of type Reference whose base object is Result(5) and whose property name is Result(6).

CMS