Constructors are special functions that create and initialize a class or object instance, learning how to create Constructors makes it possible to eradicate unnecessary lines of code and also helps in constructing a clean code base. Before we dive fully into what Object Constructors mean, let's discuss what Objects mean in JavaScript.
Object in JavaScript
Object is a major concept of JavaScript; The JavaScript language is built on objects. it can be defined as a collection of related Data. Objects are like variables, but the object variables are assigned to more than one value.
Example
JavaScript
let recruit = {
name: "Philip";
eyeColor: "Black";
Height: 5'9;
age: 28;
}
Example2
JavaScript
let club = {
name : "Manchester United",
location : "England",
established : "1878"
}
What are object constructors?
Object constructors are special JavaScript functions used in creating new or multiple instances of an object or class, it simply sets a new value into an existing object property by creating a new template.
Constructors are special functions that create and initialize a class's object instance
New objects are created using “This”
keyword.
Example
JavaScript
function recruit(name, eyecolor, height, age) {
This.name = name;
This.eyeColor = eyeColor;
This.age = age;
This.updateAge = function (){
Return ++this.age;
};
}
Here, we are done creating the object constructor template, we can now add as many as possible Objects.
JavaScript
Let recruit01 = new recruit (Philip, eyeColor, height, age) {
This.name = name;
This.eyeColor = eyeColor;
This.age = age;
This.updateAge = function (){
Return ++this.age;
Console.log(recruit01.updateAge());
First Object (recruit01 )
above.
JavaScript
Let recruit02 = new recruit (Williams, eyeColor, height, age) {
This.name = name;
This.eyeColor = eyeColor;
This.age = age;
This.updateAge = function (){
Return ++this.age;
Console.log(recruit02.updateAge());
Second object (recruit02)
.
we can create as many as possible object using this method and finally, we have the built-in constructors.
Built-in constructors in JavaScript
We also have a set of built-in constructors in JavaScript which includes the following:
Var a =new object ();
Var b = new string ();
Var d = new Number ()
Var e = new number ();
Var f = new Boolean ();
Var g = new Boolean (true);
Wrapping Up
It's safer to know what an object constructor is at a very early stage of learning the JavaScript language because the language itself is based on an object. I hope from reading this well-explained article, you got a good understanding of Objects and Object constructors in JavaScript. If you enjoyed this article, please do well to like and comment button.
Thanks for reading!