Javascript object Constructor function allows us to create multiple similar objects easily. We invoke the constructor function using the new operator. In this tutorial, let us learn what is a constructor function, how to create a constructor, how to create multiple objects using the constructor function, and the role of the new operator in invoking the constructor function.
Table of Contents
What is a Constructor function?
The constructor function is a regular JavaScript function that contains a recipe to create a new object. When we invoke it using the new operator it creates a new instance of the object and returns it.
By Convention, we capitalize the first letter of the constructor function name. But that is optional and JavaScript does not care.
What is New Operator
The new
operator lets us create and initializes a new object from a constructor function.
How to Create a Constructor function
We create a constructor function similar to the way in which we create functions in JavaScript.
The following is the example of a Constructor function Person
. The function accepts three arguments. You can pass as many arguments or no arguments to the function
1 2 3 4 5 6 7 8 9 10 | function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.fullName = function() { return this.firstName + ' ' + this.lastName; }; } |
Inside the function, we create properties and assign them to the object pointed by this
.
We invoke it with the new
operator and passing the value for each parameter. It will create a new person
object and returns it.
1 2 3 4 5 | let person = new Person('Alex', 'Ferguson', 50); console.log(person); console.log(person.fullName()); |
How New Operator works
The new
operator can be used on any function. For Example the following code works without any error.
1 2 3 4 5 6 7 | function sayHello() { console.log("hi") } new sayHello(); |
But, when we invoke any function with the new
keyword, it does the following things
- It creates an empty JavaScript object
- Adds the
__proto__
Property to the object and links it to the constructor functions prototype property. - Binds the
this
context of function to the newly created object. - If the constructor function returns an object then new will return it. Else it will return
this
. If the function returns any primitive value, it will ignore it and returnsthis
In the following example, the newClone
function shows what new operator does behind the scene
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.fullName = function () { return this.firstName + ' ' + this.lastName; }; } //This function mimics new operator function newClone(ConstFunc, ...theArgs) { //1. Creates a new object let obj = {}; //2. Sets prototype of constructor function as the prototype of newly created object Object.setPrototypeOf(obj, ConstFunc.prototype) //3. calls the ConstFunc using call and sets obj as its 'this'. let ret = ConstFunc.call(obj, ...theArgs) //4. if it returns Object then returns it as it is if (ret == Object) return ret //else return obj return obj; } //Person created using the NewClone personclone = newClone(Person, 'Alex', 'Ferguson', 50) console.log(personclone ); //Person created using the new Operator person = new Person('Alex', 'Ferguson', 50) console.log(person); |
You can compare both the objects. You will find that they are identical.
Creating Object without new
The following example shows how we can create a new object without using the new
operator. This will also create a new object identical to one using the new operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function Person(firstName, lastName, age) { //Create an empty object let obj = {}; //Assign properties & methods obj.firstName = firstName; obj.lastName = lastName; obj.age = age; obj.fullName = function() { return obj.firstName + ' ' + obj.lastName; }; //Setting the prototype of newly created object Object.setPrototypeOf(obj, Person.prototype) //return it return obj; } let person = Person('Alex', 'Ferguson', 50); console.log(person); |
The use case for Constructor Functions
The constructor function makes it easier to create as many objects as you want, using the same pattern.
1 2 3 4 5 | let person1 = new Person('Alex', 'Ferguson', 50); let person2 = new Person('Santi', 'Argo', 40); let person3 = new Person('Sarah', 'Moanees', 25); |
Built-in Objects
The JavaScript includes constructors for its built-in types. We can use the new
keyword to instantiate them as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Create an empty object. let o = new Object(); // Create an empty array let a = new Array(); // Create a Date object representing the current time let d = new Date(); // Create a Map object for key/value mapping let r = new Map(); |
Single Use constructors using new
1 2 3 4 5 6 7 | let person = new function() { this.firstName = 'Barry'; this.lastName = 'Kade'; }(); console.log(person); |
Return from constructors
The constructor function returns this
. Hence it is not common to have a return statement. But you can return any other object other than this
then the new operator will use that
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.displayName = function() { return this.firstName + ' ' + this.lastName; }; let obj = {}; obj.firstName = 'Polly'; obj.lastName = 'Pipe'; return obj; } var person = new Person('Carmen', 'Sayid'); console.log(person); ***Console*** //{firstName: "Polly", lastName: "Pipe"} |
But if you return a primitive data type like string
, number
, bigint
, boolean
, and symbol
it is ignored and this
is returned
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.displayName = function() { return this.firstName + ' ' + this.lastName; }; return '10'; } var person = new Person('Carmen', 'Sayid'); console.log(person); *** Console **** Person {firstName: "Carmen", lastName: "Sayid", displayName: ƒ} |
Constructor Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.displayName = function() { return this.firstName + ' ' + this.lastName; }; } function Car(make, model, owner) { this.make = make; this.model = model; this.owner = owner; } let Carmen = new Person('Carmen', 'Sayid'); let Polly = new Person('Polly', 'Pipe'); var Jeep = new Car('Jeep', 'Compass Sport', Carmen); var Nissan = new Car('Nissan', '300ZX', Polly); console.log(Jeep.owner.displayName()); console.log(Nissan.owner.displayName()); |
Reference
Read More