Object Oriented Programming (Subclassing in detail) - PintoGideon/Recursive-React-Tree-Component GitHub Wiki

class Person {
constructor(name) {
this.name = name;
}
describe() {
return `Person named ${this.name}`;
}
static logNames(persons) {
for (const person of persons) {
console.log(person.name);
}
}
}


class Employee extends Person {
constructor(name, title) {
super(name);
this.title = title;
}
describe() {
return super.describe() +
` (${this.title})`;
}
}
const jane = new Employee('Jane', 'CTO');
assert.equal(
jane.describe(),
'Person named Jane (CTO)');
  1. Inside a .construction() method, you must call the super-constructor via super() before you can access this. That's because this doesn't exist before the super-constructor is called.

  2. Static methods are also inherited. For example, Employee inherits the static method .logNames().

Dispatched vs Direct method calls (advanced)

class Person {
constructor(name){
this.name=name
}
describe(){
return 'Person named' + this.name
}
}
const jane=new Person('Jane');

The prototype chain of jane starts with jane and continues with Person.prototype.

Normal method calls are dispatched- the method call jane.describe() happens in two steps:

  1. Dispatch: In the prototype chain of jane, find the first property who key is describe and retrieve it's value.

const func=jane.describe;

  1. Call: Call the value, while setting this to jane. func.call(jane);

This way of dynamically looking for a method and invoking it is called dynamic dispatch.

You can make the same method call directly, without dispatching.

Person.prototype.describe.call(jane)