Changing static function in child class with Typescript

My parent class is structured as follows:

class SomeClass {

  public someProperty: number | undefined;

  constructor(value: number) {
    this.someProperty = value;
  }

  public on(eventType: string, fn: Function) {

  }
}

class Parent {

  protected static getTransform(value: number) {
    return value + 180;
  }

  public transform: SomeClass;

  constructor(value: number) {
    this.transform = this.createTransform(value);
  }

  protected createTransform(value: number) {
    const transform = new SomeClass(value);
    transform.on('rotate', this.rotate);
    return transform;
  }

  protected rotate(event: any) {
    this.transform.someProperty = Parent.getTransform(event.transform);
  }
}

To implement a child class with different logic for the transform property calculation, I have the following code snippet in mind:

class Child extends Parent {

  protected static getTransform(value: number) {
    return value + 90;
  }

  constructor(value: number) {
    super(value);
  }
}

Despite no errors, my implemented approach does not seem to work as expected. How can I achieve the desired outcome? Playground

Answer №1

... safeguarded (granting access from the same category and its subcategories, but not instances of a different group) ... Wiki: OOP

To clarify the Member Visibility concept, here is an example using your code (Please refer to the comments):

class SomeClass {

  public someProperty: number | undefined;

  constructor(value: number) {
    this.someProperty = value;
  }

  public on(eventType: string, fn: Function) {

  }
}

class Parent {

  protected static getTransform(value: number) {
    return value + 180;
  }

  public transform: SomeClass;

  constructor(value: number) {
    this.transform = this.createTransform(value);
  }

  protected createTransform(value: number) {
    const transform = new SomeClass(value);
    transform.on('rotate', this.rotate);
    return transform;
  }

  protected rotate(event: any) {
    this.transform.someProperty = Parent.getTransform(event.transform);
  }
}

class Child extends Parent {

  protected static getTransform(value: number) {
    return value + 90;
  }

  constructor(value: number) {
    super(value);
  }
}

class Example extends Child {
  constructor(value: number) {
      super(value)
    console.log(`In Example:`, Child.getTransform(700)) // this line will be executed when `new Example()`
  }

  public static getTransform(value: number) {
    return Child.getTransform(600); // calling parent method which is protected is valid
  }

}

// Usage examples:

console.log(`Invoke Child:`, Child.getTransform(800)) //  this will throw an error:
// Property 'getTransform' is protected and only accessible within class 'Child' and its subclasses.

new Example(700) // inheritance allows calling parent method which is protected

console.log(`Invoke Example:`, Example.getTransform(1000)) // calling a function that invokes a protected method from the parent is acceptable.

TypeScript Playground <- You can click the Run button to see the result and the Errors tab for error messages.

Answer №2

It seems unnecessary to reassign a static function in this scenario. Instead, consider overriding the rotate() function in Child and utilizing the Child static method:

  override rotate(event: any) {
    this.transform.someProperty = Child.getTransform(event.transform);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change the value dynamically in a single line using AngularJS

Hey there, I'm currently working on a loop situation where <div draggable="true" ng-repeat="item in items> <span>{{item.Id}}</span> <span>{{item.des}}</div> </div> I'm trying to figure out how to set ...

What is the best approach to eliminating unchecked checkboxes produced by ng-repeat when using modulo operation?

In the code snippet below, I am generating multiple checkboxes from a list and arranging them into three columns using ng-if="$index % 3 == 0". <div ng-controller="TestController" class="container"> <div ng-repeat="item in items" ng-if="$inde ...

Eliminate the hazy white layer covering the exterior of an image that has been blurred using CSS

Hey there, I've encountered an issue with an image that transitions from blurred to unblurred when the dom is loaded. <div class="image-wrapper-container2"><div class="image-wrapper orig" style="background-image: url('https://www.w3scho ...

Tips for managing numerous HTTP requests in Angular 6

I have a method that is trying to chain together 3 requests like this: showProfileDetails() { this.getUserInfo(this.currentUser.id).pipe( mergeMap(e => this.getAccounts(this.currentUser.id) ), mergeMap(e => this.getPayments ...

What is preventing my Button's onClick() method from being effective?

Below is a snippet of my HTML layout using the sciter framework: <div id="volume_micphone_slider" style="z-index:1;"> <input id="volume_slider" class="volume_slider" type="vslider" name="p1c" max="100" value="20" buddy="p1c-buddy" /> < ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

What steps can I take to address this Material UI alert and deliver a solution that adds value?

I am currently working on fetching API data (specifically category names) from the back-end (Node.js) to the front-end (React). My main objective right now is to populate a Select component from Material UI. To fetch the API data, I am utilizing Express an ...

Make sure to clear the timeout in JavaScript before re-calling the function again

Scenario: Whenever a user clicks on a cell within the "#test" table, the "update_func" function will run and repeat every 10 seconds. If the user clicks on the same cell or another cell, multiple instances of "update_func" start running simultaneously ev ...

Tips for dynamically assigning arguments to a method call within a loop

Encountered an unusual issue that can be best described through code: var fruits = ["apples", "oranges", "pears"]; var Breakfast = { _consume : function (fruit) { Breakfast[fruit]._numConsumed++; } }; for (var f in fruits) { var fruit = fruits ...

Steps to direct a locally stored video file into a video player component

Important Reminder: Avoid using static paths when setting the video source. The video component source should be dynamic, allowing users to select a file from their local device and automatically set it as the source. I've attempted this before, but ...

How to retrieve nested menu items within the scope by utilizing JSON and AngularJS

I have recently started working with angular and am facing difficulty in accessing the submenu items within my angular application. While I can successfully access the top level menu items, I am struggling to retrieve the second level items. Here is a sni ...

What is a way to receive a reply in JavaScript without using an endpoint?

Take a look at this code snippet I wrote: ... await fetch('https://example.com', { method: "GET", mode: "no-cors" }) .then((response) => { console.log(response.body); console.log(response ...

Arrange information into sections

This Angular code is used to format text into profile page as blocks of data: <div class="element-box"> <div class="details-wrapper"> <p><b class="label">Remote IP</b>{{apiattempt.remote_ip}}</p> <p>< ...

Tips on enabling the search bar to accept input and navigate to a new page

Currently, I am working on implementing a search box that redirects the user to a specific page based on their input. However, no matter what I try, it seems that when an input is provided, nothing happens. Here is the code I have been working with: <! ...

Executing the ngIf directive in Angular 2 when a function or click event occurs

Is there a way to display an element only when a specific function is executed or a particular click event occurs? Here's the html code snippet I'm currently working with: <sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [map ...

JavaScript/TypeScript Asynchronous Filtering on AsyncIterable<T>

I am currently working with an AsyncIterable variable and I am trying to apply a filter on it. Take a look at the example below (pseudo code) - class SomeClass { private SOME_CONST= "ABCDE"; private async someFunction(): Promise<strin ...

Employing JavaScript to display or conceal a <div> element while scrolling

I'm looking to create a customized sticky navigation bar through Javascript, but I have never written my own code in this language before. My approach involves implementing two sticky navigation bars that appear and disappear based on scrolling behav ...

"Exploring the world of Vue.js and videojs: refreshing the video

Is there a way to refresh the videojs in Vue (3)? Here is the code snippet I am currently using: <template> <video-js controls="true" preload="auto" ref="video_player" class="video-js vjs-big-play-centered&quo ...

Shared variables in Node.js allow for multiple users to access different entry points simultaneously

In the process of transitioning my node-js application from a single-tenant database to a multi-tenant database, I am facing some challenges. The application code is accessed through an express api and various services are run through different entrypoints ...

ReactJS is encountering a situation where two children are using the same key and causing

When I try to view the profile information of another user, I encounter a duplicate key error that says: "Warning: Encountered two children with the same key, ``. Keys should be unique so that components maintain their identity across updates. Non-unique k ...