How Property Access Works Friday, 5 October 2007
It's important for web developers to understand how the property access operators work. Here's a javascript basic lesson that every web developer should know:
(function(){
var a = "A String?";
a.isString = true;
return a.isString;
})();
What should be returned? Will it be the value true?
undefined
What happened to the isString property?
To answer that question, you need to know how the property access operator works.
The property access operator converts the value of its left hand operand (if it is a primitive) to an object and gets the property off that object.
Effectively, the above example is equivalent to:
var a = "A String?";
Object(a).isString = true;
return Object(a).isString; // undefined
An object is created, assigned the property isString with the value true, and then becomes
inaccessible by program code.
How about assigning properties to String objects?
(function(){
var a = "Axel";
a = new String(a);
a.foo = 123;
return a.foo;
})();
123
Variable a is now a String object. Objects can have properties.
The same conversion does not, unfortunately, take place with the instanceof operator.
(function(){
var a = "Al Gore";
return a instanceof String;
})();
false
It is still possible to check the constructor property of the object that is created by the
property access operator.
(function(){
var a = "avatar";
return a.constructor === String;
})();
true
The typeof operator returns "string" for string values and "object" for String objects.
(function(){
var a = "apple";
var b = new String("bork");
return typeof a + "; " + typeof b;
})();
string; object
Primitive values are not objects. Don't let the property access operators fool you.
Core JavaScript 1.5 Reference:Global Objects:StringTechnorati Tags: JavaScript


AnimTree
Garrett,
Awesome post. This is something you almost never encounter, but would be a tricky one to figure out if you did. Thanks for the FYI!