DEV Community

Alim Mohammad
Alim Mohammad

Posted on

Shadowing in JavaScript

Overview

Shadowing in a special concept in JavaScript that makes the methods belonging to the parent class redefinable in the child class.

Let us go with two of the darling games of 21st century which are pretty easy to guess, GTA and Red Dead Redemption, unless you are not a fan of open world bangers.

Image description

Back to our topic, I will give GTA the role of Parent Class and RDR takes the Child Class spot.

Code

class GTA {
  constructor() {
    this.openWorld = {};
  }

  addFeature(feature, value) {
    this.openWorld[feature] = value;
    return this.openWorld[feature];
  }
}

class RDR extends GTA {
  addFeature(feature) {
    super.addFeature(feature, true);  // Calls the parent class' method and adds the feature
    return true;
  }
}

var role = new RDR();
console.log(role.addFeature('ROLE_PLAYER'));  // This will return true
console.log(role.openWorld);  // This will now have 'ROLE_PLAYER' added to it with value true
Enter fullscreen mode Exit fullscreen mode

Explanation:

super.addFeature(feature, true) calls the addFeature method in the GTA class, adding the feature to the openWorld object.

The addFeature method in RDR returns true, but it also ensures that ROLE_PLAYER is added to the openWorld object.

Image description

Closing Note

Looks like ROLE_PLAYER just rode into the wild open world with a value of true. Hope they're ready for the bugs they'll encounter—it's an open-world game, after all!

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay