Constructor - patrickcole/learning GitHub Wiki
Constructor
A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object.
- a function object used to create and initialize objects in JavaScript
// setup or construct the Student:
function Student() {
}
// now invoke the Student:
let student = new Student();
- properties can be added to the object via the
this
context inside the constructor function or the prototype pattern
Updated Example
function Student(name, age) {
this.name = name;
this.age = age;
}
let student = new Student("Patrick", 33);
Private Fields in Constructors
Taking the previous example, let's say the Student has a numerical grade. The student or others shouldn't be able to modify that without calling a dedicated function. So let's make it private:
function Student(name, age) {
let grade = 90; // this is private and lexically scoped to the Student;
this.name = name;
this.age = age;
this.getGrade = function() {
return grade;
}
}
let student = new Student("Patrick", 33);
student.grade = 100;
console.log( student.getGrade() ); // => 90;
The grade was not modified as there is no way to modify the value outside of the object therefore making it private.
If the grade needs to be updated, it can be done via a dedicated method:
function Student(name, age) {
let grade = 90; // this is private and lexically scoped to the Student;
this.name = name;
this.age = age;
this.getGrade = function() {
return grade;
}
this.incrementGrade = function() {
grade += 1;
}
}
let student = new Student("Patrick", 33);
student.incrementGrade();
console.log( student.getGrade() ); // => 91;
Now the grade has been incremented by 1 due to the dedicated method that has access to the private property grade
.
When implementing this object with Class
, the use of get
and set
will come in handy for getting and setting values.