Sending the appropriate context using "this" to an external function within a class

Imagine a scenario where I have a simple class that extends other classes, and an object of functions that I am passing to class B

const actions = {
   doSomething: (this: B, foo: boolean) => {
      console.log('from do something', this.text, foo);
   }
}
class B {
  actions = actions;
  text: string;
  constructor() {
    this.text = 'abc';
  }
}
class A extends B {
   runAction(foo) {
      this.actions.doSomething(false);
   }
}


const instance = new A();
instance.runAction(); // 'from do something, undefined, false'

The TypeScript compiler is also indicating that the this context is incorrect when called from within runAction

Is there a more efficient way to achieve this functionality?

We need access to the class data for over 500 actions without passing arguments through each one individually.

Answer №1

This

this.operations.performAction(false);

invokes the method with a this reference to this.operations. However, this.operations is simply an object containing the performAction method - it's not the actual instance itself. To solve this, you must utilize .call along with converting the arrow function performAction into a regular function/method in order to correctly capture a different this context. It's also advisable to add types for the argument parameter (or remove it).

Ensuring type checking for this within the executeOperation function can be beneficial as well, although it may not always be necessary.

const operations = {
   performAction(this: D, argument: boolean) {
      console.log('from perform action', this.text, argument);
   }
}
class C extends D {
   executeOperation(this: C) {
      this.operations.performAction.call(this, false);
   }
}

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

Ways to retrieve text from a pdf document using JavaScript?

Is there a way to extract text from a PDF using JavaScript? I've looked into npm modules like PDF-TO-TEXT, but they require a file path name as input. I'm currently using the react-drop-to-upload module to allow users to drop PDF files onto a rea ...

What is the process of accessing JSON data transmitted from a Express server in JavaScript?

Working with a node server, I've set up a client-server model, meaning the client connects to "localhost" and express generates a response based on certain logic. While I'm able to send a JSON object through the response, I'm unsure of how t ...

We have come across a project on CodePen that utilizes Three.js, and we are looking to customize its color scheme

We stumbled upon a fascinating blob experiment on Codepen (https://codepen.io/vcomics/pen/ZwNgvX) and were eager to incorporate it into our project. However, we encountered an issue with the color changing feature on this perlin object (rcolor, gcolor, bco ...

Ways to display all utilized typescript types within a project

Here is a snippet of code I'm working with in my project: describe('Feature active', () => { it('Should render a Feature', () => { const wrapper = shallow(<MyComponent prop1={1}/>); expect(wrapper.prop('p ...

What is the best approach to integrate react-hooks, redux, and typescript seamlessly?

Struggling to seamlessly integrate React-hooks, Redux, and Typescript. It's a never-ending cycle of fixing one error only for another to pop up. Can anyone pinpoint what the root issue might be? Currently facing the following error related to my red ...

Navigate vertically using the pointer lock feature in THREE.js

I am seeking a way to achieve vertical movement using three.js's pointerlockcontrols. Specifically, I desire the movement to be similar to three.js's flycontrols, where the vertical direction of movement is proportional to the direction the user ...

ngAnimate removeClass behaving unexpectedly

Recently, I've been delving into the ngAnimate module for AngularJS version 1.2.14 When employing $animate.addClass, everything seems to function as expected with the ng-animate, -add, and -add-active classes seamlessly added. However, my struggle a ...

What is the best way to attach an event listener to detect the coordinates where a click occurs inside a div element?

Imagine a situation where you have a div container measuring 200px by 500px. The goal is to implement an event listener that can identify the x and y coordinates within this div when it is clicked. What would be the approach to achieve this in React? ...

Leveraging CustomPipe with ngModel in Angular 7 and beyond

In my application, I am facing an issue with a date calendar picker input that is storing dates on a server and returning them onInit. The problem arises when the date is not stored or picked, as it returns 01/01/0001 numbers. My goal is to have the input ...

Heroku deployment failed: Push rejected due to lack of a Cedar-supported application

Trying to deploy my 3D game (created with three.js) on a Heroku server has brought up an issue. After running the command "git push heroku master," I encountered the following problem: Initializing repository, done. Counting objects: 252, done. Delta com ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Changing the opacity of the background when a Bootstrap modal is displayedHere's how you can

While working with a bootstrap modal, I noticed that the background content opacity does not change by default when the modal is open. I attempted to change this using JavaScript: function showModal() { document.getElementById("pageContent").style.opaci ...

Executing numerous HTTP requests in a single Node.js HTTP request

I am attempting to make a single URL call that will fetch multiple URLs and store their JSON responses in an array, which will then be sent as the response to the end user. Here is what my code looks like: var express = require('express'); var ...

Exploring the creation of an Angular service that utilizes HttpClient for making GET requests, with a focus on the different

I've been diving into Angular lately and I'm facing some challenges with handling get requests. If you're interested, you can check out my code on Angular Stackblitz import { HttpClient} from '@angular/common/http'; import { Inject ...

An engaging webpage with a dynamic scroll feature

I recently inherited a dynamic HTML page that utilizes bootstrap and jqxGrid, and it calls server side code to retrieve data. However, after the data is loaded and the jqxGrid is populated, the page automatically scrolls down. Since I got the code from a ...

Using Node.js to dynamically load HTML content

I'm just starting out with NodeJs. I'm currently trying to retrieve some HTML from a website to parse it and extract information for debugging purposes. I've had success using the http module (refer to this post), but when I print the ch ...

Utilizing useLocation for Defining Text Styles

I'm currently integrating TypeScript into my project, but I'm encountering an error related to 'useLocation' in my IDE. Any thoughts on what might be causing this issue? import React from "react"; import { useHistory, useLocat ...

Exploring the Contrast between 'this' Context in V8 Javascript: Chrome versus Node.js

Check out the code snippet below: var pocket = { cash: 1000, showCash: function() { return this.cash; } }; var thomas = { name: "Thomas", work: function() { console.log('I don&bs ...

React functional components with checkboxes can trigger rerenders

I'm currently working with Gatsby and have a functional component that iterates through a set of data to generate a radio button group with an onchange event and a checked item. Whenever I update the state, the entire page component re-renders. I thou ...

Using a script to properly close HTML tags

It seems like a straightforward task, but I'm not sure where to start looking for the solution. What I'm trying to accomplish is this. I have a script that scans for the strings [gallery]. When it finds [gallery], it replaces the tag with an ima ...