0

So, I have 2 constructor functions, Person (which is parent) and Student (which is child of parent). I'm trying to implement inheritance between these constructor functions and everything is working correctly instead of one thing which breaks my logic.

This is my implementation:

//Parent
const Person = function (this: PersonI, firstName: string, birthYear: number) {
    this.firstName = firstName;
    this.birthYear = birthYear;
}

Person.prototype.calcAge = function () {
    console.log(2040 - this.birthYear);
}

//Child
const Student = function (this: StudentI, firstName: string, birthYear: number, course: string) {
    Person.call(this, firstName, birthYear);
    this.course = course;
}

//Inheritance
Object.setPrototypeOf(Student.prototype, Person.prototype)

Student.prototype.introduce = function () {
    console.log(`My name is ${this.firstName} and I study ${this.course}`);
}

const mike = new (Student as any)('Mike', 2020, 'CS');
console.log(mike);

And as a result in console I'm getting: enter image description here

Methods are set perfeclty in place, BUT why 'Person' is shown in marked place at screenshot instead of 'Student'?

4
  • that's weird and I can't explain it (although no doubt someone cleverer than me can) - but I wouldn't worry about it. [[Prototype]] is purely an internal property, that you can't access in JS code, and this is likely a quirk of the console on the particular browser you're using the developer tools in. Commented Dec 31, 2022 at 15:27
  • Is there a reason why we are using functions and not ES6 classes? Commented Dec 31, 2022 at 15:31
  • 1
    This is normal. Student.prototype is now a Person instance. Commented Dec 31, 2022 at 15:32
  • 1
    @vera there is no difference, same situation in the classes Commented Dec 31, 2022 at 15:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.