Home / code / javascript

Objects in Javascript

Javascript is designed on a simple object-based paradigm. An object is a construct with properties (javascript variables or other objects) and methods (function associated with the object). In addition to objects that are predefined in the navigator client (browser) and the server, you can define your own objects.

 

Object and properties

A JavaScript object has properties associated with it. You access the properties of an object with a simple notation.

objectName.propertyName

Both the object name and property are case sensitive. You define a property by assigning it a value. For example, suppose there is an object named myCar (for now just assume the object already exists). You can give it properties named make, model and year as follows:

myCar.make = "Ford"
myCar.model = "Mustang"
myCar.year =  1969

An array is an ordered set of values associated with a single variable name. Properties and arrays in JavaScript are intimately related; in fact they are different interfaces to the same data structure.
So you can also write.

myCar["make"] = "Ford"
myCar["model"] = "Mustang"
myCar["year"] =  1969

This object of array is known as an associative array, because each index element is also associated with a string value. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:

function show_props(obj, obj_name)
{
  var result = " "
  for (var i in obj)
	result += obj_name + "." + i + " = " + obj[i] +  "\n"
  return result
}

So, the function call show_props(myCar, "myCar") would return the following:

myCar.make = Ford
myCar.model = Mustang
myCar.year = 1967

Creating New Objects

Javascript has a number of predefined objects. In addition, you can create your own object. In JavaScript 1.2, you can create an object initializer. Alternative, you can first create a construction function and then instantiate an object using that function and the new operator.

Using Object Initializers

In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. "Object initializer" is consistent with the terminology used by C++.

objectName = {property1:value1, property2:value, ..., propertyn:valuen}

Where objectName is the name of the new object, each property is an identifier (either a name, a number, or a string literal), and each value is an expression whose value is assigned to the property. The objectName and assignment is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable.

If an object is created with an object initializer in a top-level script, JavaScript interprets the object each time it evaluates the expression containing the object literal. In addition, an initializer used in a function is created each time the function is called.

The following statement creates an object and assigns it to the variable x if and only if the expression cond is true.

if (cond) x = {hi="there"}

The following example creates myHonda with 3 properties. Note that the engine property is also an object with its own properties.

myHonda = {color:"red",wheels:4,engine:{cylinders:4,size:2.2}}

JavaScript 1.1 and earlier versions. you cannot use object initializers. You can create objects only using their constructor functions or using a function supplied by some other object for that purpose.

Using a Constructor Function

You can create a object with these 2 steps:

  1. Define the object type by writing a constructor function
  2. Create an instance of the object with new

To define an object type, create a function for the object type that specifies its name, properties and methods. For example, suppose you want to create an object type type for cars. You want this type of object called car, and you want it to have properties for make, model, year and color. To do this, you would write the following function:

function car(make, model, year)
{
  this.make = make
  this.model = model
  this.year = year
}

Notice the use of this to assign values to the object's properties based on the values passed to the function.

Now create an object called mycar as follows

mycar = new car("Eagle", "Talon TSi", 1993)

You can create any number of car objects by calls to new. For example:

kenscar = new car("Nissan", "300ZX", 1992)
vpgscar = new car("Mazda", "Miata", 1990)

An object cab have a property that itself is another object. For example, suppose you define an object called person follows:

function person(name, age, sex)
{
  this.name = name
  this.age = age
  this.sex = sex
}

and then instantiate 2 new person objects as follows:

rand = new person("Rand McKinnin", 33, "M")
ken = new person("Ken Jones", 39, "M")

Then you can rewrite the definition of car to include an owner property that takes a person object, as follows:

function car(make, model, year, owner)
{
  this.make = make
  this.model = model
  this.year = year
  this.owner = owner
}

To instantiate the new object, you then use the following:

car1 = new car("Eagle", "Talon TSi", 1993, rand)
car2 = new car("Nissan", "300ZX", 1992, ken)

Notice that instead of passing a literal string or integer when creating the newobjects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the owner of car2, you can access the following property.

car2.owner.name

Note that you can always add a property to a previously defined object. For example, the statement:

car2.color = "black"

Adds a property color to car1, and assigns it a value "black". However, this does not affects any other objects. To add the new property to all object of the same, you have to add the property to the definition of car object type.

Indexing Object Properties

In JavaScript1.0, you can refer to an object's properties by their property name or by their ordinal index. In JavaScript 1.1 or later, however, if you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index.

This applies when you create an object and it properties with a constructor function, as in the example of the car object type, and when you define individual properties explicitly(for example, myCar.color = "red").So if you define object properties initially with an index, such as myCar[5] = "25 mpg", you can subsequently refer to the property as myCar[5]

The exception to this rule is objects reflected from HTML, such as the forms array. You can always refer to objects in these arrays by either their ordinal number (based on where they appear in the document) of their name(if defined). For example, if the second <FROM> tag in a document has a name of "myForm", you can refer to the form as document.forms[1] or document.forms["myForm"] or document.myForm

Defining Properties for an Object Type

You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type car, and the assigns a value to the color property of the object carl.

Car.prototype.color=null
car1.color="black"

Defining Methods

A method is a function associated with an object. You define a method the same way you define a standard function. Then use the following syntax to associate the function with an existing object:

object.methodname = function_name

where object is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function.

You can then call the method in the context of the object as follows:

object.methodname(params)

You can define methods for an object for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects;

function displayCar()
{
  var result = "A beautiful " + this.year + " " + this.make
    + " " + this.model
  pretty_print(result)
}

Where pretty_print is a function to display a horizontal rule and a string. Notice the use of this to refer to the object which the method belong to.

You can make this function a method of car by adding the statement:

this.displayCar = displayCar

So the full definition would look like:

function car(make, model, year, owner)
{
  this.make = make
  this.model = model
  this.year = year
  this.owner = owner
  this.displayCar = displayCar
}

Then you can call the displayCar method for each of the object as follows:

car1.displayCar()
car2.displayCar()

Using this for Object References

Javascript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have a function called validate that validates an object's value property, given the object and the high and low values:

function validate(obj, lowval, hival)
{
  if ((obj.value < lowval || (obj.value > hival))
	alert("Invalid Value!")
}

Then you could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

<INPUT TYPE="text" NAME="age" SIZE=3 onchange="validate(this), 18, 99)">

In general, this refers to the calling object in a method.

When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks on the button, the value of the text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm

<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
   onClick="this.form.text1.value=this.form.name">
</FORM>

Deleting Objects

You can remove an object by using the delete operator.The following code shows how to remove an object.

myobj=new Number()
delete myobj  //removes the object and returns true

Javascript 1.1 You can remove an object by setting its object reference to null (if that is the last reference to the object).JavaScript finalizes the object immediately, as part of the assignment expression.

JavaScript 1.0 You cannot remove objects - they exist until you leave the page containing the object.

 

TOP

Latest script:

 

Books: