new
special operator
JS Home <<
JS Reference <<
new
Property creation.
Description
The new
special operator creates an instance of a predefined or user defined object that has a constructor function.
Syntax
Signature | Description |
---|---|
object instanceof constructor | The new special operator creates an instance of a predefined or user defined object that has a constructor function. |
Parameters
Parameter | Description |
---|---|
constructor | A function used to define the object. |
arguments | Optional arguments used within the definition. |
Returns
A newly created object of the type specified or undefined
when no constructor is found
The code below creates a new custom object constructor function overriding the Object.toString()
method. We then create a couple of objects and use our custom
toString()
method to show their values. Finally we call the constructor for our newly created objects.
// Define a custom object type constructor function (a prototype).
function HomeOwner(firstName,lastName) {
this.firstName=firstName;
this.lastName=lastName;
}
// Define a custom override function for toString().
HomeOwner.prototype.toString = function HomeOwnerToString() {
var owns = this.firstName + ' ' + this.lastName + ' owns a house!';
return owns;
}
// Create and print a HomeOwner object.
owner = new HomeOwner('Barney','Magrew');
alert(owner.toString());
// Create and print another HomeOwner object.
owner = new HomeOwner('Barney','Magrew');
alert(owner.toString());
// HomeOwner constructor (returns constructor function).
alert(owner.constructor ' constructor');
Related Tutorials
JavaScript Basic Tutorials - Lesson 7 - Objects
JavaScript Basic Tutorials - Lesson 8 - Strings
JavaScript Basic Tutorials - Lesson 9 - Booleans
JavaScript Intermediate Tutorials - Lesson 1 - Arrays
JavaScript Intermediate Tutorials - Lesson 1 - Dates and Times
JavaScript Intermediate Tutorials - Lesson 8 - Functions
JavaScript Intermediate Tutorials - Lesson 9 - Regular Expressions
JavaScript Advanced Tutorials - Lesson 2 - Errors
JavaScript Advanced Tutorials - Lesson 3 - Number
JavaScript Advanced Tutorials - Lesson 4 - Math