Building simple objects
Javascript objects are basically just hash tables, a group of related properties and functions that can be accessed by a key. Properties are dynamically added at runtime. Methods are just properties that happen to be functions.
Building a simple object
The simplest way to build objects in Javascript is by declaring a new variable of type object and assigning the properties or methods that the object needs:
-
var rufus = new Object();
-
rufus.name = "rufus";
-
rufus.species = "cat";
-
rufus.hello = function() { alert("miaow"); }
Javascript objects are dynamic. Their properties do not need to be defined before they are set. You can add a new property at any time at runtime just by assigning it. You do not need to declare data types like you do in class based languages like C# and java but you can share implementation between objects of the same type using constructor functions and object prototypes.
Notice that we have set the hello property of rufus to a function rather than a primitive data type like a string. This is possible because functions are just a special type of object in javascript. They can be treated just like a string or a number or any other data type. A javascript object’s methods are just a property that happen to be a function.
The hello function is also being declared as an anonymous function. We don’t need to declare it before we assign it to the property and it doesn’t have a name.
Dot syntax vs subscript syntax
Objects in javascript are just hashtables. There is nothing particularly special about them, they are just a collection of key/item pairs. One side effect of this is you can access their properties with either an object like dot syntax or a array like subscript syntax.
The previous example used the dot syntax to access the name, species and hello properties. Here’s the same example using the subscript syntax:
-
var casper = new Object();
-
casper["name"] = "casper";
-
casper["species"] = "bird";
-
casper["hello"] = function() { alert("squark! squark!");
-
}
There is no difference between the two syntaxes. They are just two different ways of saying the same thing and can be used interchangeably.
The advantage of the dot syntax is it looks more natural to people used to accessing object properties in languages like C# or java. Most javascript code that uses objects accesses the properties in this way.
Sometimes subscript syntax can be very useful because the key is indexed with a string. The string can be built at runtime to access an object’s properties without knowing exactly what properties it has.
For example you could use a foreach loop to iterate through each property in the object or dynamically build the property name:
-
for(var property in rufus)
-
alert(rufus[property].toString());
-
var myObject = {
-
property1: "chocolate",
-
property2: "cake",
-
property3: "brownies"
-
}
-
for(var x=1; x<4; x++)
-
alert(myObject["property" + x]);
Object literal syntax
In the first example we declared an object by calling the Object constructor function. There is a quicker (as in less typing) way to do this using something called the object literal.
The shortcut syntax object literal syntax is assigning the variable to a pair of braces. Assigning a variable to the object literal is exactly the same as calling the Object constructor:
-
var empty1 = {}; // is the same as saying – but is quicker to type
-
var empty2 = new Object();
The object literal can also be used to set up the object’s properties. The properties can be created as a list of key/value pairs. It’s very useful for when you want to initialize an object with a heap of different properties when you create it. It’s a very common thing to see in Javascript code.
Here’s the first example declared as an object literal:
-
var sabby = {
-
name : "Sabby",
-
species: "cat",
-
hello : function() { alert("hissss"); }
-
};
There is absolutely no difference between objects created with any of these syntaxes. You should choose the one that works best for what you’re doing. Once you have declared an object using the object literal syntax that, you can still use the dot or subscript syntax to add or change its properties:
-
sabby.age = 7;
When is this useful?
Creating simple objects like this is very useful for situations where you want to pass around group of related variables around a script.
Imagine a situation where you are using a library that supports custom events and you want to pass some information about your event to the function that is handling it. You could write ten lines of code to create a javascript object type that has all of the properties you need or you could write one line of code to create a simple object using object literal syntax. In most cases it will only make a difference in where the object is declared, it won’t make any difference to the code that’s using the object.
-
this.fireEvent({element: navigationElement, state : "active" });
-
…
-
function onNavigationStateChange(e){
-
// do something here
-
alert(e.element.id + " is " + e.state);
-
}
Another thing that the simple objects (particularly the object literal) is useful for is creating a set of related library functions. This is the same sort of situation where you might create a class full of static functions in C#.
Here’s an example of what an array helper library might look like:
-
var ArrayUtil = {
-
contains : function(array, element)
-
{
-
for(var x=0; x<array .length; x++)
-
{
-
if(array[x] == element)
-
return true;
-
}
-
return false;
-
},
-
exclude : function(list, items)
-
{
-
…
-
},
-
makeList : function(list)
-
{
-
…
-
}
-
}
-
var list = ["A", "B", "C"];
-
alert("Has A? " + ArrayUtil.contains(list, "A"));
What’s next?
Javascript functions are first class objects. They are just a special type of object which means you can do anything with them that you could do with any other type of object. This is important to understand when creating objects in javascript because object methods are just properties that happen to be functions.
This article is part of a set of related posts about How javascript objects work.

January 15th, 2009 at 10:42 pm
so, these two methods should produce the same results, except the latter can be reused?
// object literal
var myNewObj = {
func : function (param) {},
str : ”,
arr : [],
obj : {}
}
// function constructor
function func (param) {
this.str = ”;
this.arr = [];
this.obj = {}
}
var myNewObj = new func(param);
January 16th, 2009 at 5:04 pm
The only major difference is that the objects created with the constructor maintain a link back to the function that constructed them. This is important when you want to use the javascript language’s more advanced prototype feature to share implementation between the objects created with the same constructor, much like you would with a class in a more traditional language. I’ve got a new article about prototype coming up with some more information about that.
Another difference between your first example and the second example is that the first example has a method called func() while the second doesn’t. The object created will have a link back to it’s constructor function (object.constructor) but the func constructor won’t be available as a func() method on the object.
November 30th, 2009 at 12:46 am
Good article