When invoking a JavaScript method, the context variable 'this' is lost

I have developed a basic pointer to a method like this:

export class SmbwaService {
    getExistingArsByLab(labId: number): Observable<SmwbaAr[]> {
        this.otherMethod();
    }

    otherMethod(): void {
    }
}


let method: (x: number) => Observable<SmbwaAr[]>;
method = this.service.getExistingArsByLab;
method(12);

It runs smoothly in terms of calling the getExistingArsByLab method. However, I encounter an error when it attempts to call otherMethod because:

Cannot read property otherMethod of undefined.

What is the correct way to handle this? In my actual code, method is assigned to different methods based on certain conditions.

Answer №1

To create a function reference that is tied to a specific value of this, you can use the Function.bind method:

customMethod = this.service.getExistingArsByLab.bind(this.service)
customMethod(2)

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

Detecting collisions in JavaScript

Currently, I am in the process of reviving an old game reminiscent of Tron using HTML5 canvas and JavaScript. The unique twist in this version is that the snakes have the ability to move in curves rather than right angles (known as Achtung Die Kurve). The ...

Enhance the performance of node.js when processing data from a massive file

My dilemma lies in the challenge of reading and processing a large file with numerous rows. When dealing with small files under 50kb, everything runs smoothly. However, I am faced with a 15MB file for a programming competition, which serves as a hard input ...

Encountering a 400 bad request error while trying to retrieve an authentication token from an API url in Angular

I encountered a problem in my Angular 6 application where I am receiving an Http 400 Bad Request error when attempting to call the API url for login token. The interesting thing is that the API works perfectly fine when accessed through POSTMAN. However, ...

Navigating to a different page in the app following a document update: a step-by-step guide

I am facing an issue with a page where I am trying to print a specific DIV using the script below... function printReceiptDiv() { var divElements; if (vm.isDLR) { divElements = document.getElementById("DLRreportCont ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

Executing a CRM javascript button triggers a request to a JSON URL and extracts a specific value

My current task involves creating a button in JavaScript due to system limitations preventing the use of HTML. This button should navigate to a specific URL (REST API to retrieve a JSON file). Furthermore, upon clicking the button, I aim to display an aler ...

RectAreaLight in Three js does not produce any light reflection when used with MeshPhongMaterial due to lack of support for OES_texture_half

After trying to incorporate a RectAreaLight into my three.js scene where I have objects with MeshPhongMaterial, I noticed that there is no light reflection on the objects. A useful example can be found here: Link If you open the developer tools, you can s ...

Using Regex in Javascript to locate unfinished items that start and finish with brackets

Can anyone assist me in utilizing regex to identify any incomplete items that start with {{. I have attempted to search for instances in the string that begin with {{ and are followed by letters (a-Z) but do not end with }}. However, my attempts always re ...

Determining the width of an element in Chrome using jQuery

Before adding an element to the body, I require its width. The code below functions correctly in Firefox, however it does not work properly in Google Chrome. <style> .testDiv { width:150px; height:100px; } </style> <script> var di ...

Unable to view image when using material-ui CardMedia component

Hello, I've encountered a problem with rendering an image in my application. Let me explain the issue in a simplified manner. So, I have a card component (MyCardComponent) where I need to pass a string prop containing the image file location. The goa ...

"After clicking the button for the second time, the jQuery on-click function begins functioning properly

(Snippet: http://jsfiddle.net/qdP3j/) Looking at this HTML structure: <div id="addContactList"></div> There's an AJAX call that updates its content like so: <div id="<%= data[i].id %>"> <img src="<%= picture %&g ...

JavaScript incorrectly constructs date strings

Hey there, I've been attempting to create a JavaScript date object using a string but for some reason, it's consistently off by one day. Every time I try, it ends up showing the wrong day. Below is the code snippet in question: var date = new Da ...

Disabling eventListener upon the occurrence of another event is ineffective

I am having trouble with two functions in my app that create different HTML structures. I want to close the info button event when the menu_div button is clicked, and vice versa. Can anyone provide some help? const menu_div = document.createElement("butt ...

What is the reason behind using 'dummy' local variables to define return object keys?

I've come across a code similar to the one below on several occasions recently. One thing to observe is that modelMapper, viewMapper, and source are all defined as local variables but are not used anywhere else, except for being keys in the return ob ...

Tips for incorporating auth0 into a vue application with typescript

Being a beginner in TypeScript, I've successfully integrated Auth0 with JavaScript thanks to their provided sample code. However, I'm struggling to find any sample applications for using Vue with TypeScript. Any recommendations or resources would ...

Adjust properties based on screen size with server-side rendering compatibility

I'm currently using the alpha branch of material-ui@v5. At the moment, I have developed a custom Timeline component that functions like this: const CustomTimeline = () => { const mdDown = useMediaQuery(theme => theme.breakpoints.down("md")); ...

What is the best way for me to use a ternary operator within this code snippet?

I'm in the process of implementing a ternary operator into this snippet of code, with the intention of adding another component if the condition is false. This method is unfamiliar to me, as I've never utilized a ternary operator within blocks of ...

Trouble with Ajax program loading properly in Chrome browser

I have developed a small ajax program and encountered an issue. While it works perfectly fine on Internet Explorer 11, it does not function correctly on Chrome and Firefox. Here is the HTML file snippet: <html> <head><title>Ajax Page< ...

Acquiring information to display in a div using innerHTML

I aim to create a div that displays different animal sounds, like: Dog says Bark Bark I've attempted various methods but I'm unable to get each pair in the array to show up in a div: const animal = [ {creature: "Dog", sound: "B ...

Tips for organizing Protractor promises

I am currently experimenting with determining if an element is positioned at the bottom of a page in Protractor/Webdriver using promises. However, I feel like my current approach is quite messy and there must be a cleaner way to achieve this. describe(&ap ...