ArticleZip > Get Parent Class Name From Child With Es6

Get Parent Class Name From Child With Es6

If you're a JavaScript developer working with ES6 classes, you may have come across a situation where you need to access the name of a parent class from within a child class. This scenario might arise when you want to dynamically handle class relationships or simply need to reference the parent class for some operation. In this article, we'll delve into how you can easily retrieve the name of a parent class from a child class using ES6.

ES6 introduces a new method called `name` for functions, which also includes class constructors. By utilizing this `name` property, we can obtain the name of a class. However, directly accessing the parent class name from a child class in ES6 may seem challenging at first glance since there is no built-in method for this specific purpose. But worry not, there's a clever workaround that leverages the `constructor` property and some ES6 magic to achieve our goal.

Here's a simple piece of code that demonstrates how you can obtain the parent class name from a child class in ES6:

Javascript

class Parent {
  constructor() {
    console.log(this.constructor.name); // Output: Parent
  }
}

class Child extends Parent {
  constructor() {
    super();
    console.log(this.constructor.name); // Output: Child
    console.log(Object.getPrototypeOf(Object.getPrototypeOf(this)).constructor.name); // Output: Parent
  }
}

new Child();

In this example, we have defined two classes: `Parent` and `Child`. The `Parent` class's constructor function logs the name of the constructor, which in this case is "Parent." The `Child` class extends `Parent` and calls the parent class constructor using `super()`. Within the `Child` constructor, we log the name of the constructor, which is "Child," and then access the parent class's name using the `Object.getPrototypeOf` method.

By using `Object.getPrototypeOf(Object.getPrototypeOf(this)).constructor.name`, we are essentially traversing up the prototype chain to access the parent class and retrieve its name.

Keep in mind that this technique assumes a single level of inheritance. If you have a more complex inheritance structure, you may need to adjust the number of `Object.getPrototypeOf` calls accordingly.

By understanding how prototype chains work in JavaScript and utilizing the `constructor` property along with ES6 syntax, you can easily retrieve the parent class name from a child class. This knowledge can come in handy when you need to dynamically handle class relationships or perform operations based on class names in your ES6 code.

Hopefully, this article has shed some light on how to accomplish this task in ES6. Happy coding!

×