Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class:

var JSClass = function() {
  this.start = function() {
    console.log('JSClass.start()');
  }
}

When I call the start() method, it prints as expected:

let o1 = new JSClass();
o1.start();
// prints: JSClass.start()

However, when I attempt to extend this object with a TypeScript class like so:

class TSClass extends JSClass {
  start() {
    super.start();
    console.log('TSClass.start()');
  }

  otherStart() {
    this.start();
    console.log('TSClass.otherStart()');
  }
}

... the TSClass::start() is never called. Only the start() method defined in the JSClass.

let o2 = new TSClass();
o2.start();
o2.otherStart();

This results in:

JSClass.start()
JSClass.start()
TSClass.otherStart()

The desired output would be:

// by calling: o2.start();
JSClass.start()
TSClass.start()
// by calling: o2.otherStart();
JSClass.start()
TSClass.start()
TSClass.otherStart()

Is this behavior intentional? If so, what is the workaround for extending ES5 object methods with TypeScript?

Check out the live demo here: https://jsfiddle.net/martinsikora/2sunkmq7/

Edit: I found a solution that worked for me.

class TSClass extends JSClass {

  constructor() {
    var oldStart = this.start;
    this.start = () => {
      oldStart.call(this);
      console.log('TSClass.start()');
    }
  }
  // ...
}

Now the functionality works as expected.

Answer №1

The issue you're facing is that the start method is being added to JSClass as a class member instead of a class method.
To convert it into a method, you should add it to the prototype:

var JSClass = function () {}

JSClass.prototype.start = function () {
    console.log('JSClass.start()');
}

After making this change, the following code:

let o2 = new TSClass();
o2.start();
o2.otherStart();

Will produce the output:

JSClass.start()
TSClass.start()
JSClass.start()
TSClass.start()
TSClass.otherStart()

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

The JQuery category filtering feature malfunctions when a category consists of more than two words

Utilizing Jquery, I have implemented a feature that displays project categories and allows users to filter projects based on the selected category. To view the code pen for this implementation, please click here: https://codepen.io/saintasia/pen/dzqZov H ...

Tips for accessing nested JSON values using Selenium

Here is a JSON snippet to work with: "ACCOUNT": { "AmountDue": "$36,812.99", "OutstandingBalance": "$27,142.27", "StatementTotal": "$9,670.72", "StatementDate": "12/6/2018", "DueByDate": "12/23/2018", ...

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...

The navigation buttons on the Bootstrap carousel will only respond to keyboard commands after the arrow on the

Is there a way to change the default behavior of the bootstrap carousel to allow keyboard navigation without having to click the arrows on the screen first? In my modal, I have a carousel that I want users to be able to navigate using the keyboard arrows ...

Rotating arrows enhance the functionality of the accordion menu

I have successfully implemented a basic accordion with rotating arrows on click. Everything is working smoothly except for one issue: When I collapse one item and then try to collapse another, the previous arrow does not return to its default state. Is ...

Is the script failing to retrieve the innerHTML content?

Here is a snippet of HTML code: <div id="team_players"> <h3>Players</h3> <button class="bold-btn" onclick="teamAct('player_list');">Refresh List ↻</button> <table> <thead> <tr> ...

How to dynamically apply the orderBy filter in AngularJS

Attempting to input ordering criteria from a text box and dynamically order the content. The current code is functioning properly, but when attempting to change: orderBy:'age' to orderBy:'{{criteria}}' the functionality breaks. Her ...

Using an ng-repeat directive alongside an if condition in Angular

My website contains a vast array of 30 articles, previously represented by around 300 lines of HTML code, but now condensed to just 10 lines with angularjs. However, certain articles hold special significance and require specific display criteria. Check ou ...

Managing dependencies and automating setup processes can be tricky when incorporating Typescript into a

Query: How can I easily set up Typescript with Symfony without making extensive changes to Symphony's configuration files? Here are the key requirements for the solution: Typescript MVC Pattern should be set up in a private typescript directory: ...

What is the best way to apply custom styles in reactJs to toggle the visibility of Google Maps?

There are three radio buttons that correspond to school, restaurant, and store. Clicking on each button should display nearby locations of the selected type. Displaying Google Map and nearby places individually works fine without any issues. class Propert ...

What could be the reason behind the error related to react-router-dom?

index.tsx import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); root.render( <React.S ...

Differences in performance between Angular and JQuery_execution times

I am facing an issue on my dynamically populated Angular page. Angular sends a request to the backend using $http.get to retrieve data which then populates attributes of a controller. For example, when I call $http.get('/_car_data'), the JSON re ...

Find the months where two date ranges overlap with the help of date-fns

Is there a way to find the overlapping months between two date intervals using date-fns? const range1 = { start: new Date('2018-01-01'), end: new Date('2019-01-01') } const range2 = { start: new Date('2018-07-03'), end: new D ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Creating linear overlays in Tailwind CSS can be achieved by utilizing the `bg-gradient

Is there a way to add a linear background like this using Tailwind CSS without configuring it in tailwind.config.js? The image will be fetched from the backend, so I need the linear effect on the image from bottom to top with a soft background. Here are ...

Ensure that JavaScript functions are executed sequentially without overlapping

Important : Absolutely no jQuery allowed I have developed four distinct functions and I am looking to execute them sequentially, one after the other in JavaScript without using jQuery. I have scoured the internet for a solution but unfortunately have not ...

In Vue.js2, you can easily compare two arrays of objects that have the same values and then make changes or add properties from one array to the other

I am working with an array of objects fetched from an API (), which is linked to a variable that serves as the v-model for an input. Whenever the variable changes, so does the array through a function that triggers the API call on @keyup. The structure of ...

Grid Column with Checkboxes in Kendo UI for Vue

Seeking help in adding a checkbox column to a Kendo UI Vue grid. The column should display the values of a boolean field from the grid's data source. While I am aware of how to add a checkbox column for selection as demonstrated here: https://www.tele ...

Unable to resolve the Typescript module within a different file

I am in the process of transitioning my React app to TypeScript. Currently, everything is working fine. However, I encountered an issue after adding the TypeScript compiler and renaming files to .ts and .tsx extensions - it is now throwing a "module not fo ...

Only authenticated users are permitted to write to Firebase databases

Currently, I am in the process of setting up a new Vue JS project for a blog with Firebase integration. The main objective is to allow any logged-in user to create blog posts that are saved in the Firebase real-time database at https://xxx.firebaseio.com/b ...