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 constructorThe new special operator creates an instance of a predefined or user defined object that has a constructor function.

Parameters

Parameter Description
constructorA function used to define the object.
argumentsOptional 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');

Press the button below to action the above code:

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