JavaScript Interview Question #108
What are constructor functions?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
A constructor function is an ordinary constructable function intended to create objects when called with new. By convention its name begins with a capital letter.
Detailed Explanation
A constructor function is an ordinary constructable function intended to create objects when called with new. By convention its name begins with a capital letter.
Instance-specific data is usually assigned to this inside the constructor, while shared methods can be placed on the constructor's prototype. ES6 class syntax provides a clearer syntax for many of the same prototype-based mechanics.
Code Example
function Employee(id, name) {
this.id = id;
this.name = name;
}
Employee.prototype.getDisplayName = function () {
return `${this.id} - ${this.name}`;
};
const employee = new Employee(1, "Asif");