Back to: JavaScript Tutorial For Beginners and Professionals
JavaScript Constructor Function with Examples
In this article, I am going to discuss JavaScript Constructor Function with Examples. Please read our previous article where we discussed Object Literal in JavaScript. At the end of this article, you will understand what JavaScript Constructor Function is and when and how to use JavaScript Constructor Function with examples.
JavaScript Constructor Function with Examples
In our previous article, we created an object using the object literal (or initializer) syntax.
var person = {name: “John”, age: 15, bloodgroup: “A+” };
This allows us to create only a single object. Sometimes, we need to set an “object type” that can be used to create a number of objects of a single type. The standard way to create an “object type” is to use an object constructor function.
A method is a function, belonging to an object. It can be referenced using this keyword. this keyword is used as a reference to the current object, meaning that we can access the object’s properties and methods using it.
Syntax:
function ObjName(name) { this.name = name; } //Object constructor syntax var myobj = new ObjName("my object");
In this method, the constructor function is used to define the object, and this keyword is used to assign value to the properties. An instance of the object is created using a new keyword. we can use the new keyword to create new objects of the same type. Here, we need to create a function with arguments. Each argument value can be assigned in the current object by using this keyword in the function. this keyword refers to the current object.
Note: This is not a variable but a keyword, and its value cannot be changed.
An object can have a property that is itself another object. For example, suppose we define an object called person as follows and then create a new object i.e.: instantiate 2person objects as mentioned below:
function person(name, age, bloodgroup) { this.name = name; this.age = age; this.bloodgroup = bloodgroup; }
The above function name person is an object constructor, which accepts parameters and assigns them to the object properties using this keyword.
Creating Objects in JavaScript
Once we have an object constructor, we can use the new keyword to create a new object of the same type. And then create a new object i.e.: Instantiate two new person objects as follows:
var p1 = new person("John", 42, "A+"); var p2 = new person("Maria", 21, "B+"); document.write(p1.age); // Outputs 42 document.write(p2.name); // Outputs "Maria"
Here, p1 and p2 are now objects of the person type. Their properties are assigned to the corresponding values. The object’s properties can be accessed by using the dot notation or bracket notation syntax, as we did before. Technically, a constructor function is just a regular function used to create multiple similar objects with the following convention:
- The name of a constructor function starts with a capital letter like Person, Course, etc.
- A constructor function should be called only with the new operator.
The new operator does the following:
- Create a new empty object and assign it to this variable.
- Assign the arguments ‘John’ and ‘Maria’ to the age and name properties of the object.
- Return this value.
Adding Methods to JavaScript Constructor Functions
An object may have methods that modify its data. To add a method to an object created through the constructor function, we can use this keyword. Defining methods is done inside and outside of the constructor function.
Returning from Constructor Functions
Generally, a constructor function implicitly returns this which is set to the newly created object. But if it has a return statement, then there are the rules:
- If a return is called with an object, the constructor function returns that object instead of this.
- If a return is called with a value other than an object, it is ignored.
Example: JavaScript defines a function inside the object constructor function
<html> <head> <title> JavaScript defines function inside the object constructor function example </title> </head> <body> <script> //Way4 -Using the constructor of the Function object. //Object constructor syntax function Person(name, age, bloodgroup) { this.name = name; this.age = age; this.bloodgroup = bloodgroup; //method inside the object constructor function this.greet = function (who) { return 'Hello, ' + who + '! with age: ' + this.age + ' and bloodgroup: ' + this.bloodgroup; }; } var john = new Person("John", 42, "A+"); var maria = new Person("Maria", 21); console.log(john.greet(john.name)); console.log(maria.greet(maria.name)); </script> </body> </html>
Output: Press F12 and go to the Console section
We can change the object’s property value through the method argument. In the example below, we have defined a method named changeName for our person, which is a function, that takes a parameter name and assigns it to the name property of the object. this.name refers to the name property of the object. The changeName method changes the object’s name property to its argument.
Example: JavaScript defines a function inside the object constructor function-change object’s property value to its argument
<html> <head> <title> JavaScript defines function inside the object constructor function-change object's property value to its argument example </title> </head> <body> <script> //Way4 -Using the constructor of the Function object. //Object constructor syntax function Person(name, age, bloodgroup) { this.name = name; this.age = age; this.bloodgroup = bloodgroup; //method inside the object constructor function this.changeName = function (newName) { return this.name = newName; }; } var john = new Person("John", 42, "A+"); var maria = new Person("Maria", 21); console.log(john.changeName('Johnson')); console.log(maria.changeName('Mariyam')); </script> </body> </html>
Output: Press F12 and go to the Console section
We can also define the function outside of the object constructor function and associate it with the object.
Note: It is not necessary to write the function’s parentheses when assigning it to an object. Call the method by the property name we specified in the constructor function, rather than the function name.
Example: JavaScript defines a function outside the object constructor function & associates it with an object
<html> <head> <title> JavaScript defines the function outside the object constructor function and associates it with the object example </title> </head> <body> <script> //Way4 -Using the constructor of the Function object. //Object constructor syntax function Person(name, age, bloodgroup) { this.name = name; this.age = age; this.bloodgroup = bloodgroup; this.yearOfBirth = bornYear; } //method outside the object constructor function function bornYear() { return 2015 - this.age; } var john = new Person("John", 42, "A+"); var maria = new Person("Maria", 21); console.log(john.yearOfBirth()); console.log(maria.yearOfBirth()); </script> </body> </html>
Output: Press F12 and go to the Console section
As we can see from the above example, we have assigned the object’s yearOfBirth property to the bornYear function. This keyword is used to access the age property of the object, which is going to call the method. Call the method as usual.
In the below example, In JavaScript, functions are objects, and therefore, the method “getDetails()” gets added to the constructor function object Person itself. For that reason, we can call “Person.getDetails()”, but “member.getDetails()” throws a “TypeError“. It Throws an Error since we cannot create an object from a function.
Example: JavaScript defines a function, we cannot create an object from a function
<html> <head> <title> JavaScript defines the function, we cannot create an object from a function example</title> </head> <body> <script> //Way4 -Using the constructor of the Function object. //Object constructor syntax function Person(name, age, bloodgroup) { this.name = name; this.age = age; this.bloodgroup = bloodgroup; } const member = new Person("John", 42, "A+"); //We cannot create object from function Person.getDetails = function () { return `${this.name}, ${this.age}` }; //console.log(member.getDetails()); //throws a TypeError console.log(Person.getDetails()); //Person, undefined </script> </body> </html>
Output: Press F12 and go to the Console section
Drawbacks of the Constructor Function in JavaScript
- The drawback of the constructor function is that when we create multiple instances of the Person object, this.greet() is duplicated in every instance created, which is not good for memory efficiency.
- To resolve this, we can use the prototype (to know about this refer to using the Prototype pattern in the Object chapter) so that all instances of a custom-type object can share the same methods.
In the next article, I am going to discuss Object Constructors in JavaScript with Examples. Here, in this article, I try to explain JavaScript Constructor Function with Examples. I hope you enjoy this JavaScript Constructor Function article. I would like to have your feedback. Please post your feedback, question, or comments about this article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.