When Using TypeScript with Serverless, 'this' Becomes Undefined When Private Methods are Called from Public Methods

Currently, I am working on constructing an AWS Serverless function using TypeScript.

My focus is on creating an abstract class with a single public method that invokes some private methods.

Below is the simplified version of my TypeScript class:

export abstract class AbstractPayloadProcessor {

    private preHandlePayload(payload) {
        console.log('arrived in prehandle method')
    }

    private postHandlePayload(payload) {
        console.log('arrived in posthandle method')
    }

    protected handleException(error) {
        console.log('Exception has occurred:', error)
    }

    public processPayload(event) {

        // this line causes the issue
        this.preHandlePayload(event.payload)
        .
        .
        .
    }
}

To transpile this code into ES5, I use webpack which generates the following JavaScript output:

var AbstractPayloadProcessor = /** @class */ (function () {
    AbstractPayloadProcessor.prototype.preHandlePayload = function (payload) {
        console.log('arrived in prehandle method');
    };
    AbstractPayloadProcessor.prototype.postHandlePayload = function (payload) {
        console.log('arrived in posthandle method');
    };
    AbstractPayloadProcessor.prototype.handleException = function (error) {
        console.log('Exception has occurred:', error);
    };
    AbstractPayloadProcessor.prototype.processPayload = function (event) {
        // this line throws the exception
        this.preHandlePayload(event.payload);
        .
        .
        .
}());

The specific exception encountered is:

TypeError: Cannot read property 'preHandlePayload' of undefined

I have attempted configuring webpack to utilize ES6 and declaring functions in TypeScript using arrow functions, but both approaches result in the same exception.

The processPayload function gets triggered within the Serverless framework, though I am not familiar with its internal workings. If anyone has insights or experience with this framework, your input would be greatly welcomed.

Thank you for your attention.

Answer №1

Pure speculation

My hunch is that you might be utilizing someObject.processPayload and passing it as a callback to a function, or storing it somewhere as an event handler. This function then triggers this.preHandlePayload(), but encounters issues because its this reference is undefined due to not being called correctly.

Further details

There are various potential reasons for this becoming undefined within a method, regardless of whether it is private or public - since ultimately, they all become public after transpilation.

One probable scenario is if, for instance, in method1 you invoke method2() instead of

this.method2()</code, leading to <code>this
being undefined in method2.

Another common error involves saving a method as an event handler or employing it as a callback, like:

x.onSomething = object.method;

or

functionThatTakesCallback(object.method);

To resolve such situations, you either need to pass an anonymous function such as:

x.onSomething = (...args) => object.method(...args);

or bind the method to that object:

x.onSomething = object.method.bind(object);

Naturally, pinpointing the exact issue in your case is challenging without insight into how you actually call your methods. It's the calling, rather than the definition of methods, which typically results in undefined in this.

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

Unlocking the power of popups with Angular

As a beginner in AngularJS, I have encountered an issue where a popup appears when clicking on the "login/signup" button. Now, I want the same popup to appear when clicking on the "upload resume" button as well. Below is the code that is currently working ...

How can I retrieve the parent scope in an Angular UI nested named view?

One of the challenges I faced in my application was dealing with nested views within several screens. After experimenting with different approaches, I discovered that creating modal dialog boxes and sliding panels as actual nested states with corresponding ...

Apply CSS styling to the shadow root

In my preact project, I am creating a Shadow DOM and injecting a style element into the Shadow root using the following code: import style from "./layout/main.css"; loader(window, defaultConfig, window.document.currentScript, (el, config) => ...

Add elements to a ul element using JavaScript and make the changes permanent

Managing a dashboard website with multiple div elements can be quite tedious, especially when daily updates are required. Manually editing the HTML code is inefficient and time-consuming. Each div contains a ul element where new li items need to be added ...

The unit test is not passing due to inconsistencies between the mock data generated in the constructors and the original mock data

Currently, I am delving into the world of unit testing and have created a test to work on. Here is what I have so far: const EXEPECTED: MergedFood = { id: '1', name: 'test mergedFood', ingredients: { '2': ...

Is it possible to create dynamic backgrounds using Twitter Bootstrap's responsiveness?

Is there a way to create a responsive image arrangement for backgrounds on a website? Imagine having different background images load based on various screen resolutions. Additionally, it would be advantageous to specify different behaviors such as having ...

Guide on saving the highest score in a game using JavaScript with an if statement

I am currently working on a practice game that involves counting the number of taps made within 3 seconds. I've completed everything except for implementing the functionality to save the high score and display the previous best score if there isn&apos ...

Accessing data attributes using jQuery and the class selector

I'm looking for a way to trigger an onClick event for an entire class of elements and access their individual data attributes within the function. Typically, I would use the following method: $(".classy").click(function(){ console.log("Replace th ...

Constantly showing false values in AngularJS Firebase array objects

Encountering an issue with retrieving data from Firebase. When viewing console.log($scope.statusbaca), it shows 2 queries, true and false. However, in the app it only displays false. Apologies for any language barriers as English is not my first language. ...

Refresh page upon clicking the same state link in AngularJS using ui.router

Just received an interesting request from our QA team that seems a bit out there. Let's dive in: imagine you are already on the 'about' state/page within an angular-based app, and when you click on the 'about' state URL again from ...

Setting up Quill in a Nuxt project (a VUE component)

I'm struggling to remove the toolbar in Quill despite my efforts. This is the HTML snippet I am working with: <template> <quill v-model="content" :config="config"></quill> </template Here's what I have inside the scri ...

Implementing a feature to insert a horizontal rule button in React Draft Wysiwyg

I am currently working on implementing a custom button in React Draft Wysiwyg that will allow me to add an <hr> tag to my content. Although I have followed the demos and documentation, I have encountered an issue where the custom button successfully ...

Tips for implementing two Secondary Actions in React Material UI, with one positioned on the left corner and the other on the right, while ensuring that the behavior of the

Is there a way to display two secondary actions on either end of a list item without triggering additional onclick events? The placement can be adjusted by overriding the CSS properties right and left. https://i.stack.imgur.com/rhr7N.gif The issue arises ...

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

Is there a way to automatically fill in a text field when an option is chosen from a dropdown menu populated with a list of objects?

When working with a DTO that has attributes id, name, and text, I am creating a list of these DTOs and passing them to my JSP using model.addAttribute. In the JSP, I am rendering a Spring list in the following way: <form:select path="notificationsId" i ...

Persistent notification that just won't disappear

I've been working on improving my Notification Component in React. import React, { useEffect, useState } from "react"; import { IoMdClose } from "react-icons/io"; export type NotificationValueType = { message: string; type: & ...

What is the best way to retrieve error messages from a transaction with ethers.js?

Incorporating a custom error in my Solidity contract: error Documents__AlreadyExist(string hash); The modifier I utilize is as follows: modifier alreadyExist(string memory hash) { if (s_documentsHashes[hash]) { revert Documents__AlreadyExi ...

typescriptIs it possible to disregard the static variable and ensure that it is correctly enforced

I have the following code snippet: export class X { static foo: { bar: number; }; } const bar = X.foo.bar Unfortunately, it appears that TypeScript doesn't properly detect if X.foo could potentially be undefined. Interestingly, TypeScript ...

Encountering a syntax error close to an unexpected token '../lib/cli.js' while attempting to launch an application through pm2 start

I'm encountering an issue while executing pm2 start with an ecosystem.config.js /root/.nvm/versions/node/v18.16.0/bin/npm: line 2: require('../lib/cli.js')(process)' /root/.nvm/versions/node/v18.16.0/bin/npm: line 2: syntax error near u ...

A guide to retrieving the contents of an input field based on its assigned value and name attributes through Javascript

Can anyone help me with selecting an input element in my HTML code? Here is the input I want to select: <input id="tb-radio-gym_custom_radio-10ce67e3" type="radio" value="OUI" name="form_fields[gym_custom_radio]" data-price-inc="0" checked="checked"> ...