What is the method for invoking an outer class function from an inner function in JavaScript?

class Outer{
    private outFunction(){
       console.log("Okay!");
    }
    public functionWeCall(){
         function innerFunction(){
             this.outFunction();    //That doesn't work
         }
    }
}

I am attempting to organize the code into separate functions, but I am having trouble calling a function from the outer class within an inner function. How can this be achieved?

Answer №1

When you reach the functionWeCall() function, this starts pointing to that specific function rather than the class itself. This means that outFunction() is not accessible through this. One common workaround involves utilizing a variable like this:

class Outer {
  private outFunction() {
    console.log("Okay!");
  }

  public functionWeCall() {
    let _this = this;
    
    function innerFunction() {
        _this.outFunction();
    }
  }
}

However, it may be preferable to reconsider the structure to avoid nested functions like this.

Edit: In response to suggestions from @Aluan Haddad, here is the updated approach using an arrow function:

class Outer {
  private outFunction() {
    console.log("Okay!");
  }

  public functionWeCall() {
    () => {
      this.outFunction();
    }
  }
}

If you still want the inner function to be callable, you can assign it to a variable:

class Outer {
  private outFunction() {
    console.log("Okay!");
  }

  public functionWeCall() {
    let innerFunction = () => {
      this.outFunction();
    }
    
    innerFunction(); // this could be anywhere in the scope of functionWeCall()
  }
}

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

Declaration in Typescript for an array of strings that will be returned as a

I am facing an issue with my async function that is supposed to return either a single string or an array of strings. Here is the relevant code snippet: async getAllAnnotationTimes(): Promise<string> | Promise<string[]> { return aw ...

The best practices for managing item spacing in React or React Native

I am facing some challenges while trying to adjust the spacing of my components. My goal is to have the grid occupy 90% of the screen, with the gear icon taking up the remaining 10% <View style={{ paddingLeft: insets.left, padding ...

Animating jQuery Accordion in Horizontal Direction Extending to the Far Right

After implementing a horizontal accordion in jQuery based on the tutorial found at the following link: A minor issue arose during animation where a slight space was added on the far right side, causing the tabs to shift slightly. This problem is particula ...

What is the best way to create a carousel component with this particular design?

`I want to enhance my static HTML CSS website by incorporating a slider feature using JavaScript. Looking for guidance on the best approach. Here is the layout. I've attempted various tutorials but they weren't compatible with my layout or reli ...

What could be causing the "AJAX data not defined" error

Attempting to make an Ajax post request to the root directory on my Express server. By simply using the HTML form and submitting an artist name, I successfully receive a response back and can send the information to the client without any issues... As se ...

Is it possible to modify the class within TypeScript code while utilizing the CSS library for styling?

In my custom style sheet coustume-webkit.css, I have the following code snippet: .tabella .pagination > li:last-child > a:before, .tabella .pagination > li:last-child > span:before { padding-right: 5px; content: "avanti"; ...

Using AngularJS to bind objects with a checkbox

I am dealing with a nested list of objects that can go up to three levels deep. Each object contains another nested object, and this nesting can continue to multiple levels. I am interested in binding these objects directly to checkboxes so that when I che ...

Is there a way to retrieve all the selected values from multiple select inputs when a button is clicked in React?

I am currently working on developing a questionnaire where the select inputs' values are collected and averaged to generate a final score. Although it may sound simple, I'm facing difficulties in retrieving these values. At this point, my primary ...

Toggle the visibility of the data depending on the dropdown option chosen

Currently, I am developing an AngularJS application and facing a requirement to toggle the visibility of data based on the selected value in a dropdown list. Specifically, if the user chooses "Show" from the dropdown, the content within a tab should be dis ...

Change the structure of the JavaScript object into a new format

I humbly ask for forgiveness as I am struggling with figuring out how to accomplish this task. It seems like we need to utilize a map function or something similar, but I am having difficulty grasping it. Below is the object 'data' that I am wor ...

Looking to attach the "addEventListener" method to multiple elements that share the same class?

I'm trying to use an event listener in JS to handle the logic in the "onClick" function, but it's only executing once. I've applied the same class to all four buttons, so I'm not sure why it's only working for the first one. HTML: ...

Ways to transfer information among Angular's services and components?

Exploring the Real-Time Binding of Data Between Services and Components. Consider the scenario where isAuthenticated is a public variable within an Authentication service affecting a component's view. How can one subscribe to the changes in the isAut ...

Geometry of Rounded Corners Box - three.js

Although this question is primarily related to Math, I believe there may be alternative solutions available within threejs for my particular issue. My goal is to iterate through each vertex in a Box Geometry and determine whether it needs to be moved up o ...

core.js:15723 ERROR TypeError: Unable to access the 'OBJECT' property because it is undefined

Whenever I attempt to run this function, I encounter an issue. My goal is to retrieve the latitude and longitude of an address from Google's API. This error message pops up: core.js:15723 ERROR TypeError: Cannot read property 'geometry' of ...

Response coming from an ajax call in the form of a JSON

With the JSON string provided below: {cols:[{"id":"t","label":"Title","type":"string"},{"id":"l","label":"Avg ","type":"string"},{"id":"lb","label":"High","type":"string"},{"id":"lo","label":"Low","type":"string"}],rows:[{"c":[{"v":"Change navigation"},{"v ...

What is the process for importing unpkg url-join.js using the <script src=...> tag?

I'm encountering an issue with implementing the urlJoin function in my project. I've included the necessary library/script using a <script> tag, as the HTML is being generated by Django. <script src="https://unpkg.com/<a href="/c ...

Tips for utilizing method overload in TypeScript with a basic object?

Looking at this code snippet: type Foo = { func(a: string): void; func(b: number, a: string): void; } const f: Foo = { func(b, a) { // ??? } } An error is encountered stating: Type '(b: number, a: string) => void' is not assign ...

The reverse pagination feature of SwipeRanger is incredible for navigating through

Looking for assistance in customizing iDangerous swiper's pagination to display numbers from 10 to 1 instead of the default 1 to 10 configuration. Can someone provide guidance on how to achieve this? <!DOCTYPE html> <html lang="en> < ...

What steps can be taken to address the InvalidPipeArgument error when working with dates?

When attempting to format a date in a specific way using the pipe date, I encountered an error: Uncaught Error: InvalidPipeArgument: 'Unable to convert "25/01/2019" into a date' for pipe 'e' at Xe (main.fc4242d58c261cf678ad.js:1) ...

"Experience the power of MVC single page CRUD operations paired with dynamic grid functionality

Currently attempting to create a single page application CRUD functionality using UI Grid, however encountering an error during post request. ...