Reputation: 1050
When a class in JavaScript extends a class that has a static method, it is possible to call that method by referencing it from either the Parent class or the Child class, the results look the same, but is there any difference between them?
Example:
class MyParentClass {
static myFunction() {};
}
class MyChildClass extends MyParentClass {
anotherFunction() {
MyParentClass.myFunction();
MyChildClass.myFunction();
}
}
Both MyParentClass.myFunction();
and MyChildClass.myFunction();
both result in the same function being called. Should I be using one over the other, or is there no difference at all?
Upvotes: 2
Views: 65
Reputation: 1295
The explanation is easy, when you call parent.foo();
you are calling the parent's implementation of that function, by calling child.foo();
you are calling the child's implementation.
If you just want to call the parent's function and don't override the method in the child class there is indeed no difference between both invocations. But there is in this example:
class Parent {
static foo() {
console.log("Parent");
}
}
class Child extends Parent {
static foo() {
console.log("Child");
}
bar() {
Parent.foo(); // will print "Parent" to the console
Child.foo(); // will print "Child" to the console
}
}
Judging from this example I would suggest to always invoke child.foo()
to make it easier to maintain the code. If will overwrite the function foo()
in the future and are calling parent.foo()
but want the result of child.foo()
it will take you a while to find the mistake.
You should only invoke parent.foo()
if you explicitly need the result of the parent's implementation.
Upvotes: 3