JavaScript » Special » new

The new operator can be used to create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

To create a user-defined object type you must first define it by writing a function that specifies its name, properties and methods.

Examples

Code:
function book(title, category, author)
{
   this.title = title
   this.category = category
   this.author = author
}
Explanation:

This function creates an object for books with properties for title, category and author.

Code:
mybook = new book("The Thing", "horror", "John Lynch")
Explanation:

You can then create an instance of the object as in the following example which assigns the values "The Thing", "horror" and "John Lynch" to the respective properties.

Code:
function author(name, real_name, age)
{
   this.name = name
   this.real_name = real_name
   this.age = age
}
author1 = new author("John Lynch", "Charlie Schwarz", 43)
Explanation:

The property of an object can even be another object. You could, for example, create an object for authors and use it in the above example of the 'book' object. Again you would first define it by writing a function, and then you could create an instance of it for "John Lynch" like this.

Code:
document.write(mybook.author.age)
Explanation:

Now, as long as the 'author' object and the relevent instance of it have already been defined, the 'author' property in the 'book' object will refer to it, and you can display, say, the age of the author of 'mybook' like this.

Code:
mybook.publisher = "Centurion Books"
Explanation:

You can also add a property to any instance of an object as in this example which adds the property 'publisher' to the 'mybook' object and assigns it the value "Centurion Books".

Code:
book.prototype.publisher = null
mybook.publisher = "Centurion Books"
Explanation:

If, however, you wanted to add a property to a previously defined object type (and, therefore, all instances of it) you would have to use the prototype property. This example adds the property 'publisher' to the 'book' object type, and then assigns the value 'Centurion Books' to one particular instance of it.