JavaScript Constructor Method (original) (raw)
Last Updated : 15 Feb, 2025
A constructor in JavaScript is a special function used to create and initialize objects. It sets up object properties and is typically invoked using the new keyword. Constructors allow for the creation of multiple instances with similar properties and methods.
**In JavaScript, constructors can be defined in two main ways
- Function Constructor (Before ES6)
- Class Constructor (ES6 and Beyond)
1. **Function Constructor Method (Before ES6)
Before ES6, JavaScript used constructor functions to create and initialize objects. A constructor function is essentially a regular function that is invoked using the new keyword. Here’s how you define a constructor function.
JavaScript ``
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.getCarInfo = function () {
return ${this.year} <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>m</mi><mi>a</mi><mi>k</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">{this.make} </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.03148em;">mak</span><span class="mord mathnormal">e</span></span></span></span></span>{this.model}
;
};
}
let myCar = new Car('Toyota', 'Camry', 2020); console.log(myCar.getCarInfo());
``
- The Car function is a constructor function.
- Inside the constructor function, the this keyword refers to the new instance of the object being created. It assigns values to the make, model, and year properties.
- The getCarInfo method is also attached to the new object, which returns a string with the car’s details.
2. Class Constructor Method (ES6 and Beyond)
With the introduction of ES6, JavaScript introduced class syntax, making object-oriented programming more structured and readable. Classes provide a more modern and organized way to define constructors.
JavaScript ``
class Car { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; }
getCarInfo() {
return `${this.year} <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>m</mi><mi>a</mi><mi>k</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">{this.make} </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.03148em;">mak</span><span class="mord mathnormal">e</span></span></span></span></span>{this.model}`;
}
}
let myCar = new Car('Honda', 'Civic', 2022); console.log(myCar.getCarInfo());
``
- The Car class contains a special method called constructor(). This method is called automatically when a new instance of the class is created using the new keyword.
- The constructor() method initializes the properties (make, model, year) for the new object.
- Methods like getCarInfo can be defined directly inside the class.
How constructor works in JavaScript?
- A constructor is a special function used to create and initialize objects, defined using the function keyword or class syntax.
- The new keyword triggers the constructor, creating a new object and setting this to refer to it.
- Inside the constructor, properties are assigned to the object using this, and can be set dynamically via constructor arguments.
- The constructor implicitly returns the newly created object, allowing access to its properties and methods.
new keyword in JavaScript
The new keyword in JavaScript is used to create an object out of a constructor function in a class representation and also from the normal function’s.
JavaScript `
//Object from a function function prints(name,age) { this.name=name this.age=age } const result=new prints('Pranjal',21) console.log(result) //Object from a class class Person{ constructor(name,age) { this.name=name this.age=age } } const result1=new Person('Saurabh',30) console.log(result1)
`
Output
prints { name: 'Pranjal', age: 21 } Person { name: 'Saurabh', age: 30 }
- In the above code the new keyword is being used to convert function prints into a object named prints
- In the Person class the constructor function is being converted into an object using the new keyword
Object.create() function in JavaScript
In real life prototype means a copy of something same is the case in JavaScript here prototype means a copy of a object, function or class. Here in this scenario Object.create() is used to create a copy of a object and to copy all it’s properties into itself without the help of constructor function.
JavaScript `
const obj={ name:'Pranjal', age:21 } const obj1=Object.create(obj) obj1.class='10th' console.log(obj1.name)
`
- In the above code the obj is the first object created and then after the obj1 is created with the help of Object.create() property in JavaScript
- All the properties of obj is copied into obj1 and then can be accessed with the help of obj1
Object Factory Functions
A factory function is a regular function that returns a new object, making it a simple and reusable way to create multiple instances without using new.
JavaScript ``
function createPerson(name, age) {
return {
name: name,
age: age,
greet: function() {
console.log(Hello, my name is ${this.name}
);
}
};
}
const person1 = createPerson("Pranjal", 30); const person2 = createPerson("Vivekam", 25);
person1.greet(); person2.greet();
``
Output
Hello, my name is Pranjal Hello, my name is Vivekam
- A factory function generates and returns a new object every time it is called, making object creation simple and reusable.
- Unlike constructor functions, factory functions do not require the new keyword, reducing the chances of errors related to this binding.
- Factory functions can include private variables and additional logic inside them, improving security and modularity in code design.
- Since they don’t rely on prototypes, factory functions offer a straightforward approach, making them easier to understand and modify.
Constructor with default values
A constructor with default values allows you to specify default values for properties if no values are provided during object creation. This helps in ensuring that the object always has valid properties, even if some arguments are missing.
JavaScript `
function Person(name = "Unknown", age = 0) { this.name = name; this.age = age; }
const person1 = new Person("Pranjal", 30);
const person2 = new Person("Amar");
const person3 = new Person();
console.log(person1);
console.log(person2);
console.log(person3);
`
Output
Person { name: 'Pranjal', age: 30 } Person { name: 'Amar', age: 0 } Person { name: 'Unknown', age: 0 }
- The Person constructor is defined with default values for name and age. If no values are passed when creating an object, these defaults are used.
- The parameters name = “Unknown” and age = 0 ensure that if no values are provided, the object will still have valid properties (name and age).
- When creating person1, both name and age are provided. For person2, only the name is provided, so age defaults to 0. For person3, both name and age use the default values.
- The console.log() statements print the objects, showing how default values are applied when arguments are missing.
Constructor with method on prototypes
In JavaScript, you can add methods to the prototype of a constructor, allowing all instances created from that constructor to share the same method. This helps in optimizing memory usage, as the method is not recreated for each instance.
JavaScript ``
function Person(name, age) { this.name = name; this.age = age; }
Person.prototype.greet = function() {
console.log(Hello, my name is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mi>a</mi><mi>n</mi><mi>d</mi><mi>I</mi><mi>a</mi><mi>m</mi></mrow><annotation encoding="application/x-tex">{this.name} and I am </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal">am</span></span></span></span>{this.age} years old.
);
};
const person1 = new Person("Pranjal", 30); const person2 = new Person("Amar", 25);
person1.greet();
person2.greet();
``
Output
Hello, my name is Pranjal and I am 30 years old. Hello, my name is Amar and I am 25 years old.
- The Person constructor initializes name and age properties when a new instance is created.
- The greet() method is added to the prototype of Person. This means the method is shared across all instances of Person, saving memory.
- Instances like person1 and person2 are created using the new keyword. They inherit the greet() method from the Person.prototype.
- The greet() method is called on each instance. Since the method is shared via the prototype, both person1 and person2 can use it, demonstrating the shared behavior.
Constructor with inheritance
This code demonstrates how inheritance in classes allows a child class to inherit both properties and methods from a parent class constructor. The child class (two) inherits the name property from the parent class (one) using the super() keyword.
JavaScript ``
class one{
constructor(name)
{
this.name=name
}
greet()
{
return Hello ${this.name}
}
}
class two extends one{
constructor(name,age)
{
super(name)
this.age=age
}
greet1(){
return Your age is ${this.age}
}
}
const person1=new one('Pranjal')
const person2=new two('Pranav',21)
console.log(person2.greet())
``
- The two class inherits the name property from the one class using super(name) in its constructor.
- super(name) calls the one class’s constructor, initializing the name property in the two class.
- The two class adds its own age property, which is not present in the one class.
- When creating an instance of person2 (the two class), it inherits the name property from the one class and has its own age property.
- This demonstrates how a child class can access properties from both the parent class and its own constructor.
Advantages of constructor
- **Reusable Code: Constructors allow creating multiple instances of objects with similar properties and methods, promoting code reuse.
- **Encapsulation: They encapsulate the logic for setting up an object, keeping initialization clean and organized.
- **Object Initialization: Constructors make it easy to initialize objects with specific values (via parameters) when creating new instances.
- **Inheritance Support: Constructors enable inheritance, allowing child objects to inherit properties and methods from parent constructors.
- **Cleaner and More Maintainable Code: Constructors keep object creation logic in one place, making the code more readable and easier to maintain, especially for complex objects.
Conclusion
JavaScript constructors help developers create reusable, consistent, and well-structured objects. They simplify object initialization, support inheritance, and ensure cleaner code, making them essential in object-oriented programming. Understanding and using constructors effectively leads to more maintainable and efficient code in JavaScript.