new

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

Syntax

objectName = new objectType ( param1 [,param2] ...[,paramN] )

Parameters

Parameter Description
objectName Name of the new object instance.
objectType Object type. It must be a function that defines an object type.
param1...paramN Property values for the object. These properties are parameters defined for the objectType function.

Description

Creating a user-defined object type requires two steps:

  1. Define the object type by writing a 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. An object can have a property that is itself another object. See the examples below.
    You can always add a property to a previously defined object. However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the definition of the object type.
    You can add a property to a previously defined object type by using the Function.Function.prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type.

Examples

Example 1: Object type and object instance. 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:

Now you can create an object called mycar as follows:

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,

Example 2: Object property that is itself another object. Suppose you define an object called person as follows:

And then instantiate two new person objects as follows:

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

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

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 parameters for the owners. To find out the name of the owner of car2, you can access the following property:
car2.owner.name

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.