You can work on the prototype property directly, but it would take a disproportionate amount of effort and is probably not considered best practice. Instead, you could call the Person
constructor in the right this
context.
First of all, it is highly recommended to use Object.create
instead of the new
Operator, when assigning to the prototype
property of a function. With the new
Operator, the Person
constructor is called, but in the wrong this
context. To prevent that, you can link them like this:
Student.prototype = Object.create(Person.prototype);
Instead, if you want to call the constructor of the prototypal Link (Person
) inside Student, you could call
it in the constructor with the correct this
context:
function Student () {
Person.call(this);
this.id = "123";
}
Also, unless you want to create a single function for each instance, I would move 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 @Teemu mentioned, you could also place the name
property on the Person.prototype
to use it 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); // you only need this, if there are other things happening in the Person constructor that you need as well
this.id = "123";
}
Student.prototype = Object.create(Person.prototype);
s = new Student();
// s.name is 'no name'
s.setName("Klaus");
// s.name is 'Klaus'
this.setName = function (n) { this.name = n; }
construct at all? Why don't you writePerson.prototype.setName = function (n) { this.name = n; }
outside of yourPerson()
function?.setName
is called in the context ofs
though, which is the student. Thus the property would be ons
as well (not in the prototype). Initially, when assigningnew Person
to the prototype property ofStudent
, the property is created in its prototype as well.name
in the prototype and in the own property ofs
in context ofs
?