The constructor
property in JavaScript is a fundamental property that exists on every object. It references the constructor function that was used to create the object. The constructor
property is automatically added to the prototype of the object when it is created.
The primary purpose of the constructor
property is to identify the constructor function of an object. It can be used to determine the type of an object or to check if an object was created by a specific constructor function.
Here’s an example to demonstrate the constructor
property:
function Person(name) {
this.name = name;
}
const john = new Person('John');
console.log(john.constructor); // Output: Person(name)
The syntax of the constructor
property in JavaScript is straightforward. You can access it using the dot notation or square bracket notation.
Dot notation:
objectName.constructor
Bracket notation:
objectName['constructor']
Constructor property in JavaScript example
Simple example code.
// Define a constructor function
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
// Create an object using the constructor
const rect = new Rectangle(10, 5);
// Access the constructor property
console.log(rect.constructor);
Output:
By accessing rect.constructor
, we retrieve a reference to the Rectangle
constructor function itself. The output will be Rectangle(width, height)
indicating that the object rect
was created using the Rectangle
constructor.
The constructor
property can be particularly useful when working with object-oriented programming patterns in JavaScript, such as inheritance or polymorphism, where you might need to identify the constructor function of an object or create new objects based on the constructor of an existing object.
Comment if you have any doubts or suggestions on this JS constructor topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version