Core JavaScript 1.5 Guide:Creating New Objects:Using a Constructor Function
From MDC
[edit] Using a Constructor Function
Alternatively, you can create an object with these two steps:
- Define the object type by writing a constructor function.
- 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 for cars. You want this type of object to be called car, and you want it to have properties for make, model, and year. 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 you can create an object called mycar as follows:
mycar = new car("Eagle", "Talon TSi", 1993);
This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.
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 can have a property that is itself another object. For example, suppose you define an object called person as follows:
function person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
and then instantiate two new person objects as follows:
rand = new person("Rand McKinnon", 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 objects, 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 value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of 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
car1.color = "black"
adds a property color to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the car object type.