Javascript constructors are used to create specific types of objects.
There are native constructors, such as Object and Array.
You can define custom constructors that define properties and methods for your own type of object.
For instance, the following code uses the constructor pattern to create new objects:
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.sayName = function(){ console.log(this.name); }; } var person1 = new Person("First", 29, "writer"); var person2 = new Person("Tom", 27, "Doctor");
Here, the Person() function acts as a constructor with the following features:
The name of the function is Person with an uppercase P.
By convention, constructor functions begin with an uppercase letter, whereas non-constructor functions begin with a lowercase letter.
Using the new operator with a constructor function causes the following four steps to be taken:
In the code above person1 and person2 are each filled with a different instance of Person.
Each of these objects has a constructor property that points back to Person:
console.log(person1.constructor == Person); //true console.log(person2.constructor == Person); //true
Each of the objects in this example is considered to be both an instance of Object and an instance of Person:
console.log(person1 instanceof Object); //true console.log(person1 instanceof Person); //true console.log(person2 instanceof Object); //true console.log(person2 instanceof Person); //true
Defining your own constructors ensures that instances can be identified as a particular type.
Constructors defined in this manner are defined on the Global object.