This question already has an answer here:
- Accessing a class field on a superclass 1 answer
Please explain the difference between using a parent-child relationship using anonymous functions and using class functions? In case 1 everything works as expected. In case 2, codepen does not return any results.
//CASE 1
class Parent {
constructor(name) {
this.name = name;
}
exec() {
console.log('name', this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
exec() {
super.exec();
console.log('age', this.age);
}
}
const c = new Child('ChildName', 31);
c.exec();
//writes Childname + 31 (expected behaviour)
and
//CASE 2
class Parent {
constructor(name) {
this.name = name;
}
exec = () => {
console.log('name', this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
exec = () => {
super.exec();
console.log('age', this.age);
}
}
const c = new Child('ChildName', 31);
c.exec();
//writes nothing. Seems to crash.