Question on 'constructor functions and inheritance with call()'

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*

The best possible explanation and examples are possibly found on the MDN page about call.

The first line reads:

The call() method calls a function with a given this value and arguments provided individually.

The value of this also changes accordingly if you are running in strict-mode or not, I assume you are since your function is returning undefined instead of the global object.

Hope this helps :slight_smile:

1 Like