1

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!

1
  • 1
    "The instructor say that the prototype is Person" - no, the prototype of your abjAthlete instance is Athlete.prototype as you'd expect. The console just says that this object "looks like a Person instance" - because it inherits from Person.prototype. Commented Nov 18, 2018 at 12:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.