When a function is passed as an argument in Typescript, it may return the window object instead of the constructor

I'm still getting the hang of typescript, and I've come across a situation where a function inside a Class constructor is calling another function, but when trying to access this within sayHelloAgain(), it returns the window object instead.

Within Greeter.init(), I am using

this.sayHello("message string", parameterCallback)

class Greeter {
    init() { 
        this.sayHello("hello", this.sayHelloAgain);
    }
    sayHello(msg, callbackFunction) {
        // Returns the Greeter object
        console.log(this);
        callbackFunction(msg);
    }
    sayHelloAgain(msg) {
        // Instead of returning the Greeter object, it returns the Window object
        console.log(this)
    }
}

let greeter = new Greeter("world");

https://i.sstatic.net/rO2OJ.png

Answer №1

this is situation-based. When inside the sayHelloAgain callback, the keyword this no longer refers to an instance of your class.

To handle this issue, you can:

1 - Use .bind(this)

this.sayHello("hello", this.sayHelloAgain.bind(this));

2 - OR create a new function that invokes your callback:

this.sayHello("hello", (msg) => this.sayHelloAgain(msg));

3 - OR utilize an arrow function in your callback

this.sayHello("hello", this.sayHelloAgain);
sayHelloAgain = (msg) => { /* ... */ }

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

Is it possible to utilize JSX independently of React for embedding HTML within a script?

Is it possible to incorporate inline HTML within a script using a library such as jsx? <script src="jsx-transform.js"></script> <script type="text/jsx"> define('component', function () { return (<div>test html code< ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

Javascript syntax error: Unexpected ending of data while trying to parse JSON data at line 1, column 1

I operate a CS:GO betting platform, and I encountered an issue when attempting to access the page for withdrawing skins. After completing the reCAPTCHA verification process to confirm that I am not a robot, I received the following error: Javascript err ...

Adjustable Panel Width

Is there a way to have the width of the bottom panel expand to col-md-12 when the top panel is collapsed, and then return back to col-md-8 when the user expands the top panel again? I'm still learning, but here's what I have managed to code so f ...

React: Unexpected behavior when modifying a variable's state using post-increment

When I utilize the post-increment operator to change the state variable, the count variable retains its old value... Allow me to illustrate this with an example app: When I click the button with the following code, the app displays the following sequenc ...

Is it possible for the 'error' event to be triggered on the 'http.IncomingMessage' object during a node.js http.request?

There are 4 ways to encounter errors when calling http.get(url, cb): httpThrows() This error can occur due to a wrong format of the url or incorrect callback. function httpThrows() { try { http.get("www.missing-protocol.com", res => { ...

Unable to integrate Express.js into my React JS project

Having trouble integrating express.js into my react js Project. After adding the following lines to my app.js code: const express = require('express') const app = express(); I encounter the error messages below: - Module not found: Error: Can&ap ...

Issue encountered in Typescript: callback functions are returning undefined value when called from a superclass

As a newcomer to TypeScript and Node.js, I decided to dive into something new by exploring Angular, Node, and Express. While attempting to practice good project structure practices in Express by breaking it down into smaller parts, I encountered an issue. ...

The cookie appears in the callback URL, but does not get stored in the browser's cookie storage

I'm attempting to store the facebookPicUrl image in a cookie. Even though I can see it in the callback request, it's not showing up in the browser's cookie storage. Just to clarify, the session cookie is working fine. auth.route('/auth ...

Mocking in AngularJS: Utilizing the same service with varied functions for unit testing with Jasmine

Exploring a new service, Service A, with various functionalities: The snippet of application code is as follows: angular.module('app').factory('ServiceA', function() { var ServiceA = { _retryItem: null, retryItem: ...

Error: Import statement cannot be used outside a module (@cucumber/cucumber) while using Node.JS, Playwright, and Cucumber framework

I encountered an issue while attempting to compile my Node.js code that is compliant with ECMAScript 6: $ npx cucumber-js --require features/step_definitions/steps.ts --exit import { Before, Given, When, Then } from "@cucumber/cucumber"; ^^^^^^ ...

Controlling an AJAX request to fetch individuals

I am currently using an ajax request to display people data on the page, which is retrieved from a backend database. The search form on the page includes options for location, sector, service, and job title. Below is the javascript code being used: //var ...

ReactJS Redux Provider fails to accept the store

I'm currently in the process of migrating my redux store from using "createStore" to "configureStore" due to the deprecation of "createStore". I am working with ReactJS 17 and TypeScript, with the following versions of Redux / Redux dependencies: &quo ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

Revamp the state within a React component

I created a component that organizes logos within a grid system. The component receives 2 props: grid (which contains the logos) and limit (indicating the number of logos to be displayed). type Props = { grid: [], limit: number, }; type Sta ...

How to avoid property name conflicts when extending interfaces in Typescript

Is it possible to achieve something like this using TypeScript, such as renaming a property? interface Person { name: string age: number } interface Pet { age: string } interface Zoo extends Pet, Person {} How can we prevent this error from ...

unable to render a vector layer in openlayers 6

Currently, I am facing an issue with displaying a vector layer on an openlayers map using the source of local geojson and gpx files in my Vuejs project. Unfortunately, even when testing outside of Vue.js, the vector layer is not being displayed. Here is t ...

Tips for accessing the reference of a child when it is a functional component

Trying to implement a Higher Order Component (HOC) to access the ref of any component. It works perfectly fine when regular JSX is passed, but encounters issues when a functional component is passed: class GetRef extends React.Component { state = {}; ...

I am interested in retrieving a variable from a function

this is some unique HTML code <form id="upload"> <label for="file">Choose a File to Upload</label> <input type="file" id="file" accept=".json"> <butto ...

Angular - How to fix the issue of Async pipe not updating the View after AfterViewInit emits a new value

I have a straightforward component that contains a BehaviorSubject. Within my template, I utilize the async pipe to display the most recent value from the BehaviorSubject. When the value is emitted during the OnInit lifecycle hook, the view updates correc ...