0

I have been using Classes for ease of understand prototypes. It makes logical sense that extending a class lets you inherit from that base class. How would I do the below code using function constructors though? :

class Person {
     constructor(name,age,speciality="Not Specified") {
         this.name = name; 
         this.age = age;
         this.speciality = speciality;
     }
     sayName() {
        return this.name;
     }

}

class Athlete extends Person {

      constructor(name, age, speciality) {
          super(name,age)
          this.speciality = speciality
      }
      getSport() {
          return "I play " + this.speciality;
      }

}

let john = new Person('john', 44)

let jim = new Athlete('jim', 54, 'basketball');

I know I would have:

function Person(name,age,speciality="Not Specified") {
    this.name = name;
    this.age = age;
    this.speciality = speciality;
}

I assume I would have sayName() as a prototype rather than a property inside Person like:

   Person.prototype.sayName = function() {
        return this.name;
   }

but then how would I have an Athlete constructor that inherits these like I can do with extending a class?

Michlle95
  • 49
  • 4

1 Answers1

0

With the class, the prototype chain for an Athlete is:

instance <- Athlete.prototype <- Person.prototype

With Functions, the internal prototype of instances is the .prototype property on the function used to construct it. Just like with classes, the internal prototype of new Foo() will be Foo.prototype. So, to extend it manually, you need to set the .prototype property to an object that inherits from Person.prototype:

function Person(name, age, speciality = "Not Specified") {
  this.name = name;
  this.age = age;
  this.speciality = speciality;
}
Person.prototype.sayName = function() {
  return this.name;
}

function Athlete(name, age, speciality) {
  Person.call(this, name, age, speciality);
  this.speciality = speciality;
}

Athlete.prototype = Object.create(Person.prototype);
Athlete.prototype.getSport = function() {
  return "I play " + this.speciality;
};



let jim = new Athlete('jim', 54, 'basketball');
console.log(jim.sayName());
console.log(jim.getSport());
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320