Es6: Access To Inherited Class'es Properties And Methods From The Parent Class
Solution 1:
Yes, it's possible to call methods only defined in a subclass of an ES2015 class.
classParentClass {
constructor() {
this.childMethod();
this.initialize();
console.log(this.childProperty1);
console.log(this.childProperty2);
}
}
classChildClassextendsParentClass {
constructor() {
super();
this.childProperty1 = 'child\'s Property: OK';
}
initialize() {
this.childProperty2 = 'child\'s Property 2: OK';
}
childMethod() {
console.log('Child\'s overriden method: OK');
}
}
let childClassInstance = newChildClass();
Notice initialize()
is used to assign an initial value to childProperty2
. Parent constructor will always run before any other code in a subclass constructor, that's why childProperty1
isn't initialized when the console call was made. In a parent class, this
will point to an object with the prototype
of the subclass. In the comments section, Bergi
points out the practice of calling an overridden method in a parent constructor should be avoided, given the overriden method may depend on state not yet setup by the child constructor.
And no, it doesn't work with static methods. Even though static methods are copied to subclasses, when you refer to ParentClass
, you'll get the method defined there. There's no prototype chain to follow there.
EDIT: clarification from comments section.
Solution 2:
It is possible to refer current constructor in parent class as this
in static methods and as this.constructor
in instance methods.
This results in potential design problem, because ParentClass
doesn't have methods and properties that are defined in ChildClass
, and new ParentClass
will result in error when non-existent childMethod
is called.
Post a Comment for "Es6: Access To Inherited Class'es Properties And Methods From The Parent Class"