I try to call a method inside the parent's constructor from a child's constructor method, but I'm unable to do so. Is it possible to call the parent's method inside the constructor of the child's class?
We need this construction since we need to have access to this
in different scopes: how to do `var self = this` inside es6 class?. I created a little example code which showcases our problem:
class Foo{
constructor() {
this.classMethod = () => {
console.log('In Foo');
};
}
}
class Bar extends Foo{
constructor() {
super()
this.classMethod = () => {
console.log('In Bar');
super.classMethod(); // How to call the this.classMethod() in Foo?
};
}
}
bar = new Bar();
bar.classMethod();
Expected result should be:
In Bar
In Foo
Actual output:
In Bar
TypeError: super.classMethod is not a function
When the classMethod is moved outside the scope of the constructor, everything works as expected, except that we don't have access to var self=this
as stated in the StackOverflow question linked above.
class Foo{
constructor() { }
classMethod() {
console.log('In Foo');
};
}
class Bar extends Foo{
constructor() {
super();
}
classMethod () {
console.log('In Bar');
super.classMethod();
};
}
bar = new Bar();
bar.classMethod();
Actual output:
In Bar
In Foo
Is it possible to call a method inside the Parent's class constructor via a method inside the Child's class constructor?