Hey guys, thx for stopping by my question.
While studying constructor functions and inheritance with call(), I faced difficulty.
As you can see the full code on the bottom, I had to use
Person.call(this, name, birthYear)
in Student constructor function to inherit its ‘name’ and ‘birthYear’ from Person constructor function.
But I don’t understand WHY I MUST ADD ‘this’ with the two parameters(name, birthYear).
When I print without ‘this’ , it shows me
‘Hello I’m undefined and my major is CS’
But when I print it with ‘this’ with the two parameters, now it shows me
Hello I’m John and my major is CS
Even though I understand the outcome, I don’t clearly understand … how it works…
Can you guys help me??
If you guys can explain with an example that would be much more appreciate?!..
function Person(name, birthYear) {
this.name = name;
this.birthYear = birthYear;
}
Person.prototype.calcAge = function () {
console.log(2021 - this.birthYear);
};
function Student(name, birthYear, subjects) {
**// Question //**
Person.call(this, name, birthYear);
this.subjects = subjects;
}
Student.prototype.greet = function () {
console.log(`Hello I'm ${this.name} and my major is ${this.subjects}`);
};
const john = new Student("John", 2021, "CS");
console.log(john);
john.greet(); // *Hello I'm John and my major is CS*