What causes the undefined value of 'this' in the parent typescript class?

In my Deno Typescript project, I have the following class hierarchy:

AccountPutController.ts

export class AccountPutController extends HttpController {

    constructor(commandBus: CommandBus) {
        super(commandBus)
    }

    async handle({ params, request, response } : {
            params: { id: string }
            request: any
            response: any
        } 
    ) {
        const { value : requestBody } = await request.body()

        super.dispatch(
            new CreateAccountCommand(
                params.id,
                requestBody.username,
                requestBody.emailAddress,
                requestBody.password
            )
        )
        
        response.status = 201
    }

}

HttpController.ts

export abstract class HttpController {

    private readonly commandBus: CommandBus

    constructor(commandBus: CommandBus) {
        this.commandBus = commandBus
    }

    dispatch(command: Command) {
        if(this === undefined) {
            console.log("This is undefined")
            return
        }            
        this.commandBus.dispatch(command)
    }

}

The condition "this === undefined" is causing confusion. Can anyone explain why it evaluates true and how to prevent it?

Answer №1

this is determined by how a function is called. How are you executing the handle method?

Take a look at this example:

abstract class Abstract {
  dispatch() {
    console.log(this);
  }
}

class Concrete extends Abstract {
  handle() {
    super.dispatch()
  }
}

When you do this, it behaves as expected:

new Concrete().handle(); // this === Concrete

But if you do this, this will be undefined:

const { handle } = new Concrete();

handle(); // this === undefined

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 build script does not execute during the creation of a Node.js and React application in Visual Studio

I am currently following a detailed guide on setting up Visual Studio 2019 to develop a Node.js-React application. The link to the guide can be found here: https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-nodejs-with-react-and-jsx?view=vs ...

Best Practices for Organizing Imports in Typescript to Prevent Declaration Conflicts

When working with TypeScript, errors will be properly triggered if trying to execute the following: import * as path from "path" let path = path.join("a", "b", "c") The reason for this error is that it causes a conflict with the local declaration of &ap ...

Discovering the parameter unions in Typescript has revolutionized the way

My current interface features overloaded functions in a specific format: export interface IEvents { method(): boolean; on(name: 'eventName1', listener: (obj: SomeType) => void): void; on(name: 'eventName2', listener: (obj: Som ...

Finding the imported function in Jest Enzyme's mount() seems impossible

I'm currently facing an issue where I need to mount a component that utilizes a function from a library. This particular function is utilized within the componentDidMount lifecycle method. Here's a simplified version of what my code looks like: ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

Angular 17 isn't notifying child component of signal changes

In the statistics module, I have a signal that specifies the type of charts to display and this signal is updated through a radio button group. The signal: typeSignal = signal<string>('OIA') The radio buttons for setting the : <div clas ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

Can a function be invoked using a variable as a parameter in JavaScript?

Imagine a scenario where the need arises to use a conditional statement that performs the same action but calls a different method. const c = true; // just for illustration let b = ''; if (c) { b = 'method1'; } else { b = 'met ...

Tips for converting Javascript require to Typescript import using the const keyword

Recently, I've been attempting to import faktory_worker_node from github.com/jbielick/faktory_worker. The README provides the following instructions: const faktory = require('faktory-worker'); faktory.register('ResizeImage', asyn ...

Show information stored in Angularjs2 file (.ts) within an HTML document

Here is the code snippet from my .ts file: constructor( private config : ConfigService, private http: Http){ this.getWS('ngoName') .do((data) => { console.log(data); this.saveObj(data); }).to ...

Angular is unable to iterate through a collection of ElementRef instances

My list of ElementRef contains all my inputs, but adding listeners to them seems to indicate that textInputs is empty even though it's not. @ViewChildren('text_input') textInputs!: QueryList<ElementRef>; ngAfterViewInit(): void { ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

Exploring window event handling in Typescript (angular2)

Trying to capture events on the window object from an Angular 2 application written in TypeScript. Additionally, jQuery (imported via typings) is being used. The desired events are generated by an external library included using <script> tags in ind ...

Storing information in firebase using data structuring

While I initially passed an array to Firebase to store data, it proved to be inefficient when querying the data. As a result, I am now considering storing the data in mapping format. However, I am unsure of how to proceed with this. { "ClassDetails": ...

Eliminate any unnecessary padding from elements in angular2 components

Is there a way to remove the automatic padding added to new components in angular2? I am facing this issue with the header of my project, as shown in the image below: https://i.sstatic.net/25Zpn.png I attempted to eliminate the padding by setting it to 0 ...

Is there a way to prevent passing the mouseover event to children elements while still allowing the parent element to respond to the event across its entire area?

I am working with a dynamically generated list that contains complex components which need to perform actions on mouseover. With Angular, I attempted to implement this functionality by using (mouseover)="onhover($event)" and (mouseout)="onhover($event)" o ...

Can you explain the distinction between @types/material-ui and the official @mui/types bundle?

When it comes to npm packages, I came across @types/material-ui and @mui/types. I'm aware that the former is backed by the Definitely Typed community, but what's the reasoning behind its existence when an official types package already exists? D ...

What is the best way to merge three arrays of data into a single iterable array?

I am working on a function that fetches data from an API. In this process, I execute a total of 3 queries, each returning an array of data. My goal is to combine these 3 arrays into a single iterable array, where the indexes correspond to the original a ...

I am unable to nest children within the <Provider> tag when using Typescript Redux

https://i.sstatic.net/hFx3h.png I am encountering this error and I am unsure about the root cause. Any help would be greatly appreciated. Below, I have included a snippet of the code along with the package.json: import React from "react"; ...

Customized IntelliSense naming for overloaded parameters with conditional tuple types

In TypeScript 3.1, I have a generic function with arguments of either (TInput, string) or (string), depending on whether the generic's type parameter TInput extends undefined. To achieve this, I'm utilizing the new generic rest parameters feature ...