Saturday, January 10, 2015

Constructor

Leave a Comment
A constructor is a function that instantiates a particular type of Object. You invoke a constructor with the new keyword. Here are a few examples of constructors with built-in JavaScript objects and custom objects.

Constructor Examples
// Creates a generic object.
var myObject = new Object();
// Creates a Date object.
var myBirthday = new Date(1961, 5, 10);
// Creates a user defined object.
var myCar = new Car();

The constructor function contains the this keyword, which is a reference to a newly created empty object. It initializes the new object by creating properties and giving them initial values. The constructor returns a reference to the object it constructed.

[full_width] Writing Constructors

You can create objects using the new operator in conjunction with predefined constructor functions such as Object()Date(), and Function(). You can also create custom constructor functions that define a set of properties and methods. Here is an example of a custom constructor.

function Circle (xPoint, yPoint, radius) {
    this.x = xPoint;  // The x component of the center of the circle.
    this.y = yPoint;  // The y component of the center of the circle.
    this.r = radius;  // The radius of the circle.
}

0 comments:

Post a Comment