Grokking JavaScript Part 1 : Simple Objects
Posted by postfuturist on 2009-08-18 20:51:28

To understand JavaScript objects, you have to understand references. A variable in JavaScript is a reference to an object or a primitive value. Here is the declaration of a variable holding a numerical value:

var foo = 9;

JavaScript objects are very simple. Here is the simplest JavaScript object imaginable:
{}

JavaScript objects are maps, which is to say a collection of mappings of names to references. Here is an object which has a few named references:
{ somenumber : 99, somestring : "ninetynine"}

Usually an object is assigned to a variable (reference) so it can be referred to later.
var myobj = {foo : "bar"};

The mappings are sometimes referred to as properties. They may be accessed from a reference to an object using the dot (.) syntax or the bracket syntax.
var myobj = {mynum : 9};
document.write(myobj.mynum)); // 9
document.write(myobj["mynum"]); // 9

JavaScript objects can have properties added to them after being created.
var myobj = {foo : "something"};
myobj.bar = "hey";
myobj["baz"] = 100;
var similarobj = {foo : "something",bar : "hey",baz : 100};

There is another syntax for creating an empty object. It is related to the Java-like syntax that JavaScript uses to create objects with prototype-based inheritance (which will be explained later).
var myobj = new Object();
myobj.blah = "100";
var identical = {blah : "100"};

Since the properties of an object are references, they may refer to other objects or to the object itself, recursively.
var complexobj = {innerobj : {prop : 100}, other : 9};
document.write(complexobj.innerobj.prop); // 100
complexobj.self = complexobj;
document.write(complexobj.self.self.self.innerobj.prop); // 100

Got it?


Comment from delicious robots blog - Grokking JavaScript Part 2 : Simple Arrays:
[...] array in Javascript is a superset of an object that contains an ordered list of references. Here is the simplest Javascript array imaginable: [...]

    Leave a comment: