If you wish to modify the prototype property directly, it is possible but may require a significant amount of effort and is not usually recommended practice. A better approach would be to call the Person
constructor within the correct this
context.
It is strongly advised to utilize Object.create
instead of the new
Operator when assigning to the function's prototype
property. Using the new
Operator can cause the Person
constructor to be called in the incorrect this
context. To avoid this issue, you can establish a link like this:
Student.prototype = Object.create(Person.prototype);
If you prefer to invoke the parent constructor (Person
) within Student, you can do so by using call
in the constructor with the appropriate this
context:
function Student() {
Person.call(this);
this.id = "123";
}
In addition, to prevent creating a separate function for each instance, consider moving the setName
function to the [[Prototype]]
of Person
:
function Person() {
this.name = "no name";
}
Person.prototype.setName = function(n) {
this.name = n;
}
function Student() {
Person.call(this); // Call the Person constructor
this.id = "123";
}
Student.prototype = Object.create(Person.prototype);
s = new Student();
// s.name is 'no name'
s.setName("Klaus");
// s.name is 'Klaus'
Alternatively, as mentioned by @Teemu, you could also define the name
property on the Person.prototype
to serve as a default value:
function Person() {
}
Person.prototype.setName = function(n) {
this.name = n;
}
Person.prototype.name = "no name"; // Define the name directly
function Student() {
Person.call(this); // only necessary if other operations are required from the Person constructor
this.id = "123";
}
Student.prototype = Object.create(Person.prototype);
s = new Student();
// s.name is 'no name'
s.setName("Klaus");
// s.name is 'Klaus'