Invoke multiple stored functions using JavaScript, beginning with this one

One way to store and call a function later is by assigning it to a variable, like so:

var storedFunction = functionName;

//Later On
storedFunction(); //Equivalent to functionName()

If you want to store a function and also execute 'this' when called, you can do it like this:

var storedFunction = this.function1().function2();

Then, when you call the stored function later, 'this' will refer to the class context:

class MyClass {
    method() {
        storedFunction();
    }
}

Answer №1

Consider a scenario where you have a function structured like this:

function myFunction(){
    return {
        function inner(){
            return 'some data'
        }
    }
}

Upon calling myFunction and receiving its return value, you will get an object in the following format:

{
    inner: function (){ return 'some data'; }  
}

If you wish to save the inner function, simply store it along with its key from the returned object, like so:

let myInnerFunction = myFunction().inner;

...

//then when you want to use it
myInnerFunction()

In your situation, the correct approach would be:

let storedFunction = this.function1().function2;

If you want to execute both function1 and function2 simultaneously when called, you can achieve this through a simple method:

let storedFunction = () => {
    return this.function1().function2();
}

// or without arrow function

let storedFunction = function () {
    return this.function1().function2();
}.bind(this)

Answer №2

The dot operator (.) is known as the object access operator. When you come across it in code (not associated with a number), it indicates an attempt to access a property or method (function) of an object.

For example, this.something is trying to access the something property of an object referred to as this.

Similarly, function1().function2() implies that function2() must be a method of an object. However, the object must be returned from function1() for this to function correctly.

To better illustrate this concept, here is some sample code:

function function1() {
  return {
    function2: () => {
      console.log('called function2 from function1 on "this"');
    }
  }
}
function1.bind(this);
this.function1().function2();

// Using class syntax

class OtherClass {
  function2() {
    console.log('Used class keyword');
  }
}

class MyClass {

  constructor() {
    this.veryOddThingToDo = this.function1().function2;
  }

  function1() {
    return new OtherClass();
  }
}

const myClass = new MyClass();
// Get reference to function2() from "MyClass.function1()" call
const oddness = myClass.veryOddThingToDo;

// This is exactly: this.function1().function2() referenced"
oddness();

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

The 404 error is handled by the express application before continuing to other routes. Some routes may not be recognized by the express.Router module

Shown below is the content of app.js: var express = require('express'); var routes = require('./routes/index'); app = express(); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next ...

What distinguishes locally installed packages from globally installed packages?

What is the difference between packages installed using this command? $ npm i -g <package_name> and packages installed using the following command? $ npm i <package_name> ...

Dropdown for state selection within WooCommerce for specific countries

I am encountering a challenge in configuring a form with default WooCommerce country and states selection dropdowns. Essentially, my goal is to present the Country selection first, followed by the State selection based on the chosen country. For instance, ...

Enhancing the Ext.ux.grid.RowEditor by implementing tooltips for the save and cancel buttons

I am looking to implement tooltip messages for the save and cancel buttons in Ext.ux.grid.RowEditor. For example, I want the save button to have a tooltip that says "Save the records" and the cancel button to have a tooltip that says "Cancel saving the rec ...

Submit button in React form not activating the onSubmit method

Having an issue with a login form code where the submit handler is not being triggered when pressing the Submit button. Any idea what could be causing this? The loginHandler function does not seem to trigger, but the handleInputChange function works fine. ...

Is there a way to efficiently fetch localStorage data upon launching a React application and seamlessly store it in Redux using the useEffect hook without experiencing any data loss issues?

Should I avoid mixing React hooks and mapStateToProps in my application and instead use Redux hooks like useSelector? In my React app, I have an array of 'friend' data stored in Redux. Using useEffect in one of my components, I am saving this da ...

How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a ...

What is the most efficient way to update a large batch of documents in MongoDB?

I need to efficiently update a large number of documents (> 100,000). Initially, I attempted to do this on the JS level by writing scripts that fetch _ids first and then loop through them to invoke updates by _id (full docs or $set patches). However, ...

Opt for employing a JavaScript variable over a JSON file

Let's start with a declaration: <div id="timeline-embed"></div> <script type="text/javascript"> var timeline_config = { width: "100%", height: "100%", debug: true, rows: 2, ...

What is the best way to include a class in the <td> element of a dynamic table?

My goal is to sum up the values in a specific column of a dynamic table by attaching an id property to each row. I am specifically focused on assigning an id to each <td> in every row of the table. UPDATE: Although I have all 4 keys in the <td> ...

Steps for mocking an async action creator in Redux using Jest

I am currently working on writing a unit test for a redux async action creator using jest. asyncActions.js: const startSignInRequest = () => ({ type: START_SIGNIN_REQUEST }); // this is the action creator for successfully signing in a user export c ...

Tips for rearranging table columns using drag and drop in react js

I have been experimenting with various libraries to create a drag-and-drop feature for changing table columns order. Here is my current implementation: import React, { useState } from 'react'; import './list_de_tournees.css' const Table ...

Having issues with Sequelize and SQLite auto increment functionality. No errors when using AutoIncrement, but the auto increment feature is not working. On the other hand, errors arise when using

I am currently in the process of developing a discord bot, which includes 2 slash commands. One command is called /setup, used for adding the guildId and an adminChannel to a database. The other command is named /onduty, which is used for adding the user, ...

Setting field names and values dynamically in MongoDB can be achieved by using variables to dynamically build the update query

I am working on a website where users can place ads, but since the ads can vary greatly in content, I need to be able to set the field name and field value based on user input. To achieve this, I am considering creating an array inside each document to sto ...

What sets Java classes apart from JavaScript classes?

After working with C# and Java, I decided to dive into learning javascript/node.js. However, I am facing some challenges trying to understand what is wrong with this code. Here is the snippet from my main.js file: const MyClass = require("./MyClass"); le ...

Unable to launch React Native project on emulator now

Something seems off with my App as it won't start up on my AS Emulator. Everything was running smoothly yesterday, but today it's not working - possibly due to me moving the npm and npm-cache folders, although they are configured correctly with n ...

Accessing JSON key by value alone

Imagine you have a variable storing the value of a key in a JSON object. Let's see... var stooges = [ {"id" : "a", "name" : "Moe"}, {"id" : "b", "name" : "Larry"}, {"id" : "c", "name" : "Shemp"} ]; var stooge = "Larry"; I am seeking gui ...

Is requestAnimationFrame necessary for rendering in three.js?

I am currently working on the example provided in Chapter 2 of the WebGL Up and Running book. My goal is to display a static texture-mapped cube. The initial code snippet is not functioning as expected: var camera = null, renderer = null, scene = null ...

I encounter an error message stating "Cannot read property 'push' of undefined" when trying to add an item to a property within an interface

I have a model defined like this : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode[]; } export interface TrackMode { trackNumber: number; ...

Text Box Driven Date Selection using Asp.Net's Date Picker Control

I have 2 text boxes that accept dates from a calendar control. One is for the "From" date and the other is for the "To" date. Here's how I would like the dates to be handled: For the first text box (From), it should only allow today's date or an ...