Home > Web Front-end > JS Tutorial > body text

Shadowing in JavaScript

WBOY
Release: 2024-08-29 13:40:34
Original
313 people have browsed it

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.

Shadowing in JavaScript

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
Copy after login

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.

Shadowing in JavaScript

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!

The above is the detailed content of Shadowing in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template