Is it possible for a method within a variable in Typescript to invoke another method?

I need to execute a random function in my code. Here is what I have:

module A {

    ...

    export function foo(): number {

        let b = new B();

        let possibleFunctions = [
            b.possibleFunction1,
            b.possibleFunction2
        ];
        let index = Math.floor(Math.random() * 2);
        possibleFunctions[index](_var_);
    }

    class B {

        public usefulFunction() {
            console.log("bbbb");
            ...
        }

        public possibleFunction1() {
            ...
            console.log("aaaa");
            this.usefulFunction(); 
            console.log("cccc");
        }

        public possibleFunction2() {
            ...
        }

    }

}

The program only seems to output "aaaa" and the usefulFunciton() is never called, resulting in an error.

When I replace

possibleFunctions[index](_var_);

with

possibleFunction1(_var_);

everything works as expected.

This led me to wonder:

1. Is my observation accurate?

2. If so, why does it happen? Is the function deep-copied somehow?

3. What is the correct approach to resolve this?

Thank you!

Answer №1

The issue you are facing is due to the idiosyncrasies of the this keyword in JavaScript. Its behavior differs from that in most other programming languages, where the object referenced by this remains consistent. In JavaScript, however, the value of this can vary depending on how a function is called. One way to resolve this problem is by using the apply method:

 possibleFunctions[index].apply(b, argsArray);

In this case, the first parameter of apply specifies the object that will serve as the context for this, while the second parameter is an array containing the arguments to be passed to the function.


Another approach, as suggested by @Ced, is to use the bind method to explicitly bind your function to the correct context:

let possibleFunctions = [
       b.possibleFunction1.bind(b), 
       b.possibleFunction2.bind(b) 
    ];

By employing bind, you ensure that the value of this within the functions will always refer to the object b, regardless of the invocation method.

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

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

Can you explain the step-by-step process of how an await/async program runs in TypeScript/JavaScript or Python?

As a C++ developer specializing in multithreading, I've been diving into the intricacies of async/await. It's been a challenge for me as these concepts differ from how C++ programs are typically executed. I grasp the concept of Promise objects, ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

Acquiring information from a Service and saving it in a Child component - Angular version 11

Utilizing my service, I fetch API data for the child component. Initially, it retrieves the Id and other user data, displaying it in the console. ngOnInit(): void { this.commonService.userSetChange.subscribe( apiData => { this.getUserS ...

Is it possible that CSS is being impacted by DomSanitizer and Renderer2, causing issues with the flow and inheritance of styles?

As I embark on creating my own Calendar with Angular, I am faced with the challenge of utilizing innerHTML while ensuring safety measures are in place. Admittedly, I am new to this and must confess that my code may not be the most elegant. Following tutori ...

Universal key and attribute retrieval function

Currently, I am attempting to analyze the characteristics of objects within arrays. In order to maintain type safety, I am utilizing a getter function to access the child object of the array objects (if necessary) that contains the specific property to be ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

Limit an object to only contain interface properties

Suppose we have the following object: o {a : 1, b : 2} and this interface defined as: interface MyInterface { a : number } We are now looking to create a new object that represents the "intersection" of o and the MyInterface: o2 : {a : 1} The mai ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

Incorporate MUX Player (Video) into Angular versions 14 or 15

Mux offers a video API service with its own player: MUX Player I am interested in integrating this npm package specifically into a component in Angular 14/15. The JavaScript should only be loaded when this particular component is rendered. Integration Th ...

Hear the alteration of the JavaScript variable

Suppose there exists a code snippet at point 2 var point2IsReady = true; At point 1, I am tasked with implementing the following logic: Once the value of point2IsReady is changed (to true), then display an alert saying 'ready!'. Considerations: ...

What is the best way to delete previously entered characters in the "confirm password" field after editing the password

Is there a way to automatically remove characters in the confirm password field if characters are removed from the password field? Currently, when characters are entered into the password field, characters can also be entered into the confirm password fiel ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

Rounding Decimals using JavaScript

I am facing the challenge described in this particular query. In most cases, my code works fine to round numbers to two decimal places with the following formula: Math.round(num * 100) / 100 However, there was a peculiar scenario where it failed. When tr ...

Steps to resolve the issue of 'type is not assignable to any' while working with a member

I'm facing an issue with a code snippet like the one below: interface IFoo { bar: string; baz: number; } function f(foo: IFoo, name: 'bar' | 'baz', val: any) { foo[name] = val; // <<< error: Type 'any' i ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

Using Typescript for Asynchronous Https Requests

I've been attempting all day to make an https request work. My current code isn't functioning as expected; when I run it, I encounter an "Unhandled error RangeError: Maximum call stack size exceeded at Function.entries" import * as https from &q ...

Fetching FormControl from Directive in Angular

Is there a way to dynamically add validators to a FormControl through a custom Directive? @Directive({ selector: "[idNumber]", }) export class IdNumberDirective implements OnInit { constructor(private formControl: FormControl) { } ngOnInit() ...

Typescript React: Implementing type definitions for JSS classes object

Here is the react code I am working with: import React from 'react'; import withStyles from "react-jss"; const styles = { box: { border: "2px solid #000" } }; interface ComponentProps {} class Welcom ...

Leveraging the Angular (2) routerLinkActive directive to handle dynamic routes

Although my current approach works, I believe there may be a more efficient way to implement this in Angular. The situation is as follows: Imagine nested, inflected paths like /logos and /logo/:id The markup below functions as intended: <li class ...