JavaScript Examples

JavaScript Menu

Home

  


Primer on JavaScript Objects

JavaScript is an object-oriented language. However, it is not a class-based based language like Java or C++, but a prototype-based OO language. This means that JavaScript does not make a distinction between a class and its instance. In JavaScript, for example you can dynamically add a method to a prototype and all objects will have it, no matter when they were created. 

There are two ways to construct an object in JavaScript:

  • using object initializers (JavaScript 1.2 and later only - not explained here)
  • using constructor function

You can use any method to create an object. You just have to call it with new operator. Here is an example:

function createCar( make, model )
{
    
this.make = make;
     this.model = model;

     this.model = printValues; // printValues() is a global function
}

myCar = new CreateCar("Audi", "100 CS");
alert(myCar.make + " " + myCar.model);

The above example also illustrates that in order to create a new property of a function all you have to do is assign it some value. We can also do that after the object was already created:

myCar.color = "Blue";

In the same fashion we can assign a pointer to a function:

myCar.toString = printProperties;

In JavaScript 1.0 you cannot delete the objects - they exist until you leave the page. In JavaScript 1.1 you can assign the object a null value and it will get deleted from memory. In later versions you can use delete myObject;


Inheritance (Object Prototypes)

Inheritance is possible in JavaScript. All you have to do is assign the prototype property of the object to the new instance of the object you would like to extend. In the following example Manager object extends from Employee object:

function Manager () {...}
Manager.prototype = new Employee;

JavaScript does not allow multiple inheritance, but the constructor can call other constructors because for JavaScript their simply methods.


Dynamic Object Modification

In JavaScript, you can add properties to any object at run time. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you assign a value to the object, as follows:

mark = new Manager("Mark");
mark.bonus = 3000;

Now, the mark object has a bonus property, but no other Manager has this property.

If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement:

Employee.prototype.specialty = "none";

As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none".