`
Constructor functions provide an optimal way to create objects using a predefined prototype. The objects are created using a new keyword. JavaScript supports multiple ways of creating object as defined here and constructor functions is one of them.
Since good understanding of constructor functions is crucial for learning object oriented concepts, let’s try to understand it through a problem.
Problem statement
We want to create multiple objects of type “student” with properties as firstName, obtainedMarks, checkResults function.
Solutions
This approach is very buggy as it requires defining the complete object every time.
var maxMarks = 500;
var student = {
firstName: "firstName1",
obtainedMarks: 200,
checkResults: function () {
let percentage = (student.obtainedMarks / maxMarks) * 100;
if (percentage >= 40) {
return "pass";
} else {
return "fail";
}
},
};
student.checkResults();
The drawback of this approach is, once the object “student1” is created, it doesn’t have any relation to the student function and does not inherit the prototype of the student function . Therefore in case any additional property is added to the function “student” after object creation, the corresponding object will not inherit those.
var maxMarks = 500;
function student(firstName, obtainedMarksArg) {
return {
firstName: firstName,
obtainedMarks: obtainedMarksArg,
checkResults: function () {
let percentage = (obtainedMarksArg / maxMarks) * 100;
if (percentage >= 40) {
return "pass";
} else {
return "fail";
}
},
};
}
var student1 = student("firstName5", 100);
console.log(student1) // Output: {firstName: 'firstName5', obtainedMarks: 100, checkResults: ƒ}
student1.__proto__ === student.prototype // Output: false
This solution is most optimal as it resolves all the issues encountered in both of the previous aproaches. In the below example, notice the below 2 points: * usage of “this” keyword in binding the object properties * the equality of object’s __proto__ property with the prototype of the function
var maxMarks = 500;
// new keyword to be used with a function
function student(firstName, obtainedMarksArg) {
console.log(this); // student1 object
this.firstNameObj = firstName;
this.obtainedMarks = obtainedMarksArg;
this.checkResults = function () {
console.log(this);
let percentage = (this.obtainedMarks / maxMarks) * 100;
if (percentage >= 40) {
return "pass";
} else {
return "fail";
}
};
}
// As the JavaSript encounters "new" keyboard, it "this" inside the function with left hand side assignment variable.
var student1 = new student("firstName5", 100);
console.log(student1) // Output: student {firstNameObj: 'firstName5', obtainedMarks: 100, checkResults: ƒ}
student1.__proto__ === student.prototype // Output: true
When JavaScript encounters the “new” keyboard, it binds “this” inside the function with left hand side assignment variable (object reference)