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)');
-
Inside a
.construction() method
, you must call the super-constructor via super() before you can accessthis
. That's becausethis
doesn't exist before the super-constructor is called. -
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:
- Dispatch: In the prototype chain of
jane
, find the first property who key isdescribe
and retrieve it's value.
const func=jane.describe;
- Call: Call the value, while setting
this
tojane
. 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)