The current state of this scenario is not clearly defined within the parent class

Here is the scenario that caught my attention:

abstract class Base {
    public _obj = { name: 'Test' }

    print1() {
        console.log(this._obj)
    }

    print2() {
        console.log(this)
    }
}

class Child extends Base {
    print2() { // overriding
        // do some stuff
        console.log(this._obj)
    }
}

function test(cb: any) {
    cb()
}

const obj = new Child()
obj.print1() // works fine!
obj.print2() // works fine!
test(obj.print1) // returns undefined

Playground

When printing this, it shows up as undefined. If I pass the function as a parameter, why does the context of this get lost?

Appreciate your insights.

Answer №1

How come the this context is lost when passing a function as a parameter?

Understanding how this behaves in JavaScript is crucial. Your code illustrates the issue:

function test(cb: any) {
    cb() // `this` becomes undefined
}

Solution

A simple fix would be to pass a function that does not rely on this, for example: test(() => obj.print1())

Complete Code Example:

abstract class Base {
    public _obj = { name: 'Test' }

    print1() {
        console.log(this._obj)
    }

    print2() {
        console.log(this)
    }
}

class Child extends Base {
    print2() {
        console.log(this._obj)
    }
}

function test(cb: any) {
    cb() // `this` becomes undefined
}

const obj = new Child()
obj.print1() 
obj.print2() 
test(() => obj.print1())

Further Reading

Check out my video on this topic 🌹

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

What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>( data: T, normalize?: (data: T) => NT, ) { const normalizedData = normalize ? normalize(data) : {}; return Object.keys(normalizedData); } customFuncti ...

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

Bring in properties from a separate file in Vue3

Currently, I am utilizing Vue3 along with the options API. Within my setup, there are various Vue components that rely on a shared prop defined as: exercise: { type: Object as PropType<Exercise>, required: true, }, To streamline this pro ...

Consolidate type definition within a tsx file using VS Code

Whenever I define a type in a TypeScript file (.ts) on VS Code, I notice that there is no option to collapse the definition. Here's an example: export type Test = { someValue: string, someOtherValue: string, yetAnotherValue: string }; I ...

Receiving contextual information from Microsoft Teams within an Angular application integrated as a tab

I am currently integrating an Angular website into a Microsoft Teams tab. In order to perform certain computations, I need to retrieve the Team ID. To achieve this, I have recently added npm install --save @microsoft/teams-js. Below is the code snippet th ...

Typescript - unexpected behavior when using imported JavaScript types:

I am struggling with headaches trying to integrate an automatically generated JavaScript library into TypeScript... I have packaged the JavaScript library and d.ts file into an npm package, installed the npm package, and the typings modules in the TypeScr ...

What is the best way to trigger a function in React when a constant value is updated?

In my React application, I have 3 components. The parent component and two child components named EziSchedule and EziTransaction. Each component fetches its own data from an API. The data to display in the EziTransaction child component depends on the reco ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

The module located at "c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx" does not have a default export available

I am currently delving into the realm of RxJs. Even after installing rxjs in package.json, why am I still encountering an error that says [ts] Module '"c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx"' has no default export ...

Vue's computed property utilizing typed variables

I am trying to create a computed array of type Todo[], but I keep encountering this specific error: No overload matches this call. Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<T ...

Yup will throw an error if both a minimum value is set and the field is also marked

I am attempting to validate my schema using yup: import * as yup from "yup"; let schema = yup.object().shape({ name: yup.string().min(5) }); const x = { name: "" }; // Check validity schema .validate(x, { abortEarly: false }) . ...

Delete element from the array upon removal from the AutoComplete component

I am facing a challenge with the Material UI AutoComplete component in my project. The issue arises when I try to update the state of the associateList after clearing a TextField. Additionally, I would appreciate any guidance on how to handle removing an ...

Steps for importing jQuery typings into TypeScript:1. First, install the jQuery

I've searched for similar questions, but haven't found one that matches my issue. Can someone help me figure out what to do next? In my Visual Studio project, I used package.json to download jquery typings into the node_modules folder: { "ver ...

What is the best way to iterate through a collection of two or more arrays in order to determine the total length of all

https://i.stack.imgur.com/PpFlB.pngI currently have multiple Arrays containing various inputs this.listNumber = [ { "GenericQuestions": [ { "input": "long", }, { "input": & ...

Maintaining database consistency for multiple clients making simultaneous requests in Postgres with Typeorm and Express

My backend app is being built using Express, Typescript, Typeorm, and Postgres. Let's consider a table named Restaurant with columns: restaurant_id order (Integer) quota (Integer) The aim is to set an upper limit on the number of orders a restaura ...

When importing a React Component with styling into the pages folder, it fails to function properly

I created a component in my components directory with custom styling: // import Link from "next/link"; import {Link} from "react-scroll" export default function Navbar() { return ( <div className="fixed w-full h-[79px] fle ...

The specified 'IArguments' type does not qualify as an array type

Currently working on crafting a personalized logger. It's a fairly straightforward process, but I'm running into some errors that are muddying up my output. Here's what I have so far: @Injectable() export class Logger { log(...args: any ...

Tips on Importing a Javascript Module from an external javascript file into an <script> tag within an HTML file

I'm facing an issue while attempting to import the 'JSZip' module from an external node package called JSZip in my HTML File. The usual method of importing it directly using the import command is not working: <script> import ...

Activate TypeScript EMCAScript 6 support for Cordova projects in Visual Studio

I am interested in utilizing the async/await feature of TypeScript in my VS2015 Cordova project. I have updated "target": "es6" in tsconfig.json Although there are no errors shown in intellisense, I encounter the following error while building the project ...