What is causing Typescript to execute an overridden child method from the parent class when child.listen() is called?

class Base {

    serverSetup(){
        console.log("BaseClass")
    }

    listen() {
        this.serverSetup();
    }
}

class Child extends Base {

    serverSetup() {
        console.log("ChildClass")
    }
}

const child = new Child();
child.listen();

Why is the output ChildClass? It seems like this in the Base class should only access the serverSetup method in its own class. Is there a way to invoke the listen function from the child instance and have it first execute the Base class' serverSetup() method without using super.serverSetup() within the Child class?

Answer №1

this within a function's context is determined by how it is invoked. In this scenario, since it is executed on the child instance, the setupServer method of the child will be invoked.

The reason why removing the setupServer method from the base class results in an error in TypeScript:

class Base {

    listen() {
        this.setupServer();
    }
}

class Child extends Base {

    setupServer() {
     console.log("ChildClass")
    }
}

const child = new Child();
child.listen();

The explanation is straightforward - if you were to create an object from the Base Class at any point, calling this.listen() would cause failure. TypeScript prevents this behavior even if the setupServer function is later defined in the child class.

Answer №2

Even if you extend another class, each instance remains unique and maintains its identity even when interacting with methods from the superclass.

For instance, in the scenario you provided, when the execute method of the Parent class calls this.runTask(), the reference to this still points to child, which is an instance of Child. As a result, the search for the runTask method will start at the level of Child.

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

Occasionally, the former PHP session variable will be retrieved

On my webpage, there are user-selectable options and a button that triggers the execution of a PHP script. The result is then displayed in a div which refreshes with another PHP file utilizing a session variable created during the initial PHP script. Howev ...

Horizontally position the main word from the D3-WordCloud in the center

I am working on a WordCloud project and have utilized code from Jason Davies D3-JavaScript-WordCloud Example, which can be found at this link. The majority of the code I have used is from a helpful tutorial in German by Lars Ebert, available at this URL. ...

What is the best way to implement a Facebook share button using the Facebook Javascript SDK within an Ajax request?

In my Rails application, I have implemented the following code in an Ajax call: <script type="text/javascript"> $(document).on('click','#share_button', function(e){ e.preventDefault(); FB.ui({ method: &apo ...

Ways to Conceal/Deactivate Information in HTML

Welcome to my website mycareerpath.co.in. I am looking to remove the "FREE DOMAIN + 1GB HOSTING" from my site. Can anyone provide guidance on how to do this? Important Reminder Please remember to right click and inspect the page source for more informati ...

Is it possible to utilize html5mode with a Node server in AngularJS?

I am currently working on developing an Angularjs app locally using the same node web server as referenced in the Angularjs tutorial. You can find the code for the web-server on Github by following this link. My issue lies in getting html5mode to function ...

What is the best way to send multiple requests for the same file and retrieve the necessary response in PHP using jQuery AJAX?

var postID = $post->ID; $.ajax({ type: "POST", url: "<?php echo get_template_directory_uri();?>/b.php", data:{postID:postID}, dataType: 'json', success: function(re ...

When invoking mongoose .save() in Node.js, it experiences delays when dealing with three levels of nested subdocuments

Currently, I am immersed in the world of mongoose and node.js. These are the schemas I am utilizing (abbreviated for brevity): var gameSchema = new Schema({ gameId: { type: Number }, rounds: [Round.schema] }); var roundSchema = new Schema({ ...

use javascript to color the image based on a specified number or percentage

Looking for a method to dynamically fill an image based on a percentage. Is there a dynamic approach or is it simpler to create images at specific intervals? I am working with Angular and need to set the percentage of a 1 to 5 rating system from AJAX. h ...

Navigational issues while incorporating path.join with __dirname in node.js

Can you clarify the distinction between using path.join(__dirname, "src/js") and simply __dirname + "src/js") in a node.js environment? ...

What could be causing Highchart to return the error message "Typeerror: undefined variable byte"?

My current project involves creating a graph using highchart and updating values every second. I am also working on displaying data in Mb, Kb, and Gb format on the graph by developing a function to convert byte values. Here is a snippet of my code: // hi ...

Verification of input on ng-repeat table

I am working on an AngularJS app and have a table with ng-repeat where I have textboxes in td. I want to validate these textboxes so I tried using ng-form and ng-class, but I keep getting an invalid expression error. Here is my code: <input name ="abc ...

Is it possible for bs.reload(*.html) to refresh all HTML files located within the app directory?

Does browser-sync automatically refresh all HTML files within the app directory when Node is started with this configuration? // require the module as normal var bs = require("browser-sync").create(); // .init starts the server bs.init({ server: "./a ...

Unleashing the power of DOM events through jQuery observables

I'm a bit confused at the moment. I'm working with an Angular project using a Bootstrap theme. Someone has implemented tab functionality using Bootstrap, but there's an issue - it's all written in JavaScript. This means that events such ...

Is there a way to bring this specific function into a separate file?

There's a common practice where anonymous functions (arrow functions) are exported as default from one file. My question is, how can this be imported and used in another file? If I export the following function that returns an Object containing store ...

Refreshing the page does not update the API requests

I have been working on implementing a feature in Angular 7 where clicking on a refresh button reloads the route (without refreshing the entire page) and refreshes the data by making all API calls again. The refresh click functionality is being used across ...

Unable to change the value of a variable in a function in AngularJS

Calling all developers for assistance! I am experiencing an issue with updating a value dynamically inside an AngularJS controller that is being passed to an HTML tag. Everything works perfectly when updating the value outside of a function: var app = angu ...

In TypeScript, what specific type or class does a dynamically imported module belong to?

Can someone assist me in determining the type of an imported module in TypeScript? Here is my query: I have a module called module.ts export class RSL1 {}; Next, I import it into my index.ts using the following code: const script = await import('mod ...

What steps do I need to take to set up an SSH CLI Endpoint on my NodeJS Server?

Recently, I came across a library called ssh2 which is designed to handle connections to SSH Servers and also host SSH Servers. However, when attempting to use the code provided on their NPM page, I encountered a persistent issue where the shell would clos ...

How can I enable editing for specific cells in Angular ag-grid?

How can I make certain cells in a column editable in angular ag-grid? I have a grid with a column named "status" which is a dropdown field and should only be editable for specific initial values. The dropdown options for the Status column are A, B, C. When ...

Tips for incorporating the useContext hook into Next JS using .tsx files?

I am attempting to incorporate a dual theme (dark & light) in Next JS using MUI with the useContext method. Encountering this error: ⨯ src\app\page.tsx (6:50) @ useThemeContext ⨯ TypeError: (0, _providers_theme_context_provider__WEBPACK_IM ...