Edansys

My WordPress Blog

Feb

22

How to create objects in JavaScript


This post goes over the various methods of creating objects in JavaScript.

Objects in JavaScript are actually like associative arrays with a special dot notation making the syntax look more Java like. It is possible to use array notation to access members of an object.

anObject.aProperty = "Hello";
anObject.aFunction();
anObject["aProperty"] = "Hello";
anObject["aFunction"]();

Array notation is useful when the property or function name is derived programmatically at runtime.

The following sections detail different ways to create objects in JavaScript.

1. Start with Object

Object is the base class of all objects in JavaScript. Perhaps the quickest way to create an object in JavaScript is to create a new Object and add to it.

var person = new Object();
person.nameFirst = "John";
person.nameLast = "Doe";

person.speak = function() {
   alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
}

person.speak();

In this example, a new Object is created with the variable person pointing to it. Next, properties nameFirst and nameLast are added. Finally, a speak function is added to the person object.

Note the use of this in the above (and following) examples to reference members of the current object. Runtime binding ties this to the current object.

2. Using JavaScript Object Notation

JSON is another way to accomplish the definition of the person object. The JSON method looks a little cleaner than our first approach of starting with Object and it visually groups the definition of the object’s properties and functions between curly braces.

var person = {
   nameFirst : "John",
   nameLast : "Doe",
   speak : function() {
      alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
   }
};

person.speak();

JSON is often used to marshal data between objects in another language and JavaScript. Libraries are available in many languages that can serialize objects to and deserialize objects from JSON. Since the resulting JSON string is native JavaScript, it is very easy on the JavaScript side of the transaction to get objects this way.

3. Define a Class

With the previous two methods of object creation, we are defining object instances. The whole process has to be repeated for each additional object instance needed. Defining a class saves a lot of repetitive typing if multiple instances of a given class are needed.

function personClass() {
   this.speak = function() {
      alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
   }
}

var person = new personClass()
person.nameFirst = "John";
person.nameLast = "Doe";
person.speak();

To define a class in JavaScript, start with a function definition. Functions are themselves objects in JavaScript. This function serves as the constructor for the class. After defining the class, use the new keyword to create object instances of that class.

In this example, each object instance is created with a speak function. The properties have been added after the class was created. The properties could have been put in the class definition and assigned via the constructor function like so:

function personClass(first, last) {
   this.nameFirst = first;
   this.nameLast = last;

   this.speak = function() {
      alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
   }
}

var person = new personClass("John", "Doe");
person.speak();

4. Inheritance via Prototypes

The main problem with the first three methods of object creation is that each object instance has it’s own copy of the properties and function objects defined. This becomes memory wasteful as more objects get created.

There is a better way in JavaScript. A way in which we define all common properties and functions in one place and have every object of the same type reference them. This is done through an object’s prototype property. Every JavaScript object has a prototype property.

JavaScript implements inheritance with a prototype model instead of the classic method used in languages like Java or C++. The prototype property references another object that acts as the parent object during property and function lookups. So when a function is called on a JavaScript object, JavaScript will first look in that object for the definition of the function. If the function is not found, JavaScript proceeds to look in the prototype object for the definition. If the function is still not found, the prototype’s prototype is searched. This prototype chaining continues until either the object is found or the base of the prototype chain is reached. The value undefined is returned if the property or function being searched for is not found.

At the base of every prototype chain is JavaScript’s Object. This is how all objects get common functions like toString().

function personClass(first, last) {
   this.nameFirst = first;
   this.nameLast = last;
}

personClass.prototype.speak = function() {
   alert("Hello, my name is " + this.nameFirst + " " + this.nameLast + ".");
}

var person = new personClass("John", "Doe");
person.speak();

In this example, every object instance of personClass gets it’s own copy of the variable data nameFirst and nameLast and shares a common speak function.

The next example shows setting an objects prototype object explicitly.

/* Common base class */
function Dog() { }

Dog.prototype.barkSound = "woof! woof!";

Dog.prototype.bark = function() {
   alert(this.barkSound);
}

/* BigDog inherits from Dog */
function BigDog() { }
BigDog.prototype = new Dog();
BigDog.prototype.barkSound = "WOOF! WOOF!";

/* LittleDog also inherits from Dog */
function LittleDog() { }
LittleDog.prototype = new Dog();
LittleDog.prototype.barkSound = "yap! yap!";

/* Listening to the different types of dogs barking */
var mutt = new Dog();
mutt.bark();

var germanShephard = new BigDog();
germanShephard.bark();

var chihuahua = new LittleDog();
chihuahua.bark();

JavaScript objects can be modified dynamically at runtime. This includes prototype objects. Dynamically modifying a prototype object effectively modifies every instance associated to the prototype. It is also possible to modify the prototypes of built-in Javascript objects.

The choice of which object creation method to use depends largely on the situation. Using prototypes is overall the most flexible. JSON will probably be used for marshalling data between a client and server. The simpler methods are probably sufficient for quick transient objects.

This post just scratches the surface of what is possible with JavaScript. The dynamic nature of the language makes for some very flexible runtime constructs with objects.

Tags :

Leave a Reply