Home > Web Front-end > JS Tutorial > How do Static Method Calls Behave in ES6 Classes with Inheritance and Overriding?

How do Static Method Calls Behave in ES6 Classes with Inheritance and Overriding?

Mary-Kate Olsen
Release: 2024-11-17 17:28:02
Original
687 people have browsed it

How do Static Method Calls Behave in ES6 Classes with Inheritance and Overriding?

Calling Static Methods from ES6 Class Methods

In ES6 classes, there are two common ways to call static methods: through the constructor or through the class name itself. While both approaches are valid, they exhibit distinct behaviors in the context of inheritance with overridden static methods.

Using this.constructor to refer to the static property results in dynamic dispatch, which means it references the class of the current instance. This is useful when dealing with overridden static methods, as seen in the example below:

class Super {
  static whoami() {
    return "Super";
  }
}
class Sub extends Super {
  static whoami() {
    return "Sub";
  }
}

new Sub().whoami(); // "Sub"
Copy after login

In this case, the whoami static method is overridden in the Sub class. When called through this.constructor, it refers to the Sub class and correctly returns "Sub."

On the other hand, using the class name to refer to the static property ensures constant access to the original static method, even if it's overridden. For example:

class AnotherSuper {
  static whoami() {
    return "AnotherSuper";
  }
}
class AnotherSub extends AnotherSuper {
  static whoami() {
    return "AnotherSub";
  }
}

AnotherSub.whoami(); // "AnotherSuper"
Copy after login

Even though whoami is overridden in AnotherSub, calling it through the class name ("AnotherSub") still returns "AnotherSuper" because it refers to the static property of the AnotherSuper class.

Ultimately, the choice of which approach to use depends on the expected behavior. If the static property should always refer to the current class, use the explicit reference (this.constructor). Otherwise, use the class name to ensure constant access to the original static method.

The above is the detailed content of How do Static Method Calls Behave in ES6 Classes with Inheritance and Overriding?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template