user9608350
user9608350

Reputation:

Object.create and inheritance in JavaScript

I'm learning about Object.create and inheritance in JavaScript from an Udemy course and I have a missunderstanding. And I want to ask you if you can help me to understand how it works. Thank you in advance!

For example I have this simple line of code:

var Person = function(name, yearOfBirth, job) {
    this.name = name;
    this.yearOfBirth = yearOfBirth;
    this.job = job;
};

Person.prototype.calculateAge = function() {
    var age = new Date().getFullYear() - this.yearOfBirth;
    console.log(age);
};

var Athlete = function(name, yearOfBirth, job, olympicGames, medals) {
    Person.call(this, name, yearOfBirth, job);
    this.olympicGames = olympicGames;
    this.medals = medals;
};

Athlete.prototype = Object.create(Person.prototype);
Athlete.prototype.constructor = Athlete; 

var objAthlete = new Athlete('Mark', 1990, 'swimmer', 3, 10);

I want to ask you if it is mandatory to put this line of code:

Person.call(this, name, yearOfBirth, job);

Can I change the Athlete constructor with the following code:

var Athlete = function(name, yearOfBirth, job, olympicGames, medals) {
    this.name = name;
    this.yearOfBirth = yearOfBirth;
    this.job = job;     
    this.olympicGames = olympicGames;
    this.medals = medals;
};

I understand why we use Object.create and why we assign the correct value to the constructor property of the prototype, but I don't understand if it is mandatory the line of code.

And another question is about _ proto _, I know about prototype and "dunder" proto, but I don't understand it in the following situation.

For example if I write console.dir(abjAthlete) I get this output in the console:

enter image description here

The instructor say that the prototype is Person, and that means that the Athlete function constructor prototype property is the same that Person prototype property. How is that possible because if I write Athlete.__proto__ === Person.prototype I receive false. I really apreciate any feedback!

Upvotes: 1

Views: 40

Answers (1)

Bergi
Bergi

Reputation: 664246

I want to ask you if it is mandatory to put this line of code:

Person.call(this, name, yearOfBirth, job);

Can I change the Athlete constructor with the following code?

Yes, you could, and it would have exactly the same effect. However, you would now have duplicated the initialisation code for Persons, and that's a bad practice. Don't repeat yourself and just call the Person constructor that already knows how to initialise those properties.

Upvotes: 1

Related Questions