Using JavaScript to dynamically invoke a function and pass parameters dynamically

Exploring a dynamic method call with parameters in JavaScript.

let obj = {
  method: 'foo1',
  params: ['one', 'two']
}

foo1(p1, p2) {
 // do something
}

To execute it =>

[obj.method](obj.params)

Is there a way to dynamically add parameters from an array?

Answer №1

Affirmative - distribution (ES6):

window[obj.method](...obj.params);

Ensure that you are calling the function correctly - if you define it with var in the global scope, it will be linked to the window. If not, it will not be reachable at all (unless using eval, but that is considered poor practice).

Answer №2

If you want to call a function using a string name, you can use the following method:

window[obj.method](...obj.params)

Here is an example to illustrate this concept:

let obj = {
    method: 'foo1',
    params: ['one', 'two']
}

function foo1(parameter1, parameter2) {
    console.log(parameter1, parameter2)
}

window[obj.method](...obj.params) // output: one two

Answer №3

If you want a function to be part of an object and then invoke it dynamically using bracket notation [] with the method's name as a string inside the brackets, you can achieve that easily. The spread operator ... is used to convert the parameter array into a list.

While some examples show using the global window object as the parent, keep in mind that it is better to avoid globals and create your own object instead.

In the code snippet below, there are multiple methods and parameter options presented for the user to choose from. This selection process could be handled differently depending on the requirements.

// Store the methods within an object so they can be accessed using bracket notation
// later on.
let obj = {
  method1: function foo1(p1, p2) {
            console.log("method1 was called with: ", arguments);
  },
  method2: function foo1(p1, p2) {
            console.log("method2 was called with: ", arguments);
  },
  params1: ['one', 'two'],
  params2: ['three', 'four'],  
};

// Ask the user for their desired method and parameters:
let choice = prompt("Enter 'method1' or 'method2'");
let args = prompt("Enter 'params1' or 'params2'");

// Retrieve the method by its name (as a string) from the object to get the property value.
// Then call the method using () and access the correct parameter property in a similar manner.
// Use the spread operator (...) to flatten the parameter array.
obj[choice](...obj[args]);

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

Utilize a jQuery class selector to retrieve the value of a textbox through HTMLHelper

How can I retrieve the value of "StudentID" in a JavaScript function using jQuery? HTML: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Student.Models.vwStudent>>" %> <div class="divClass"> ...

Create a JavaScript code snippet that replaces the innerHTML of the function document.getElementById with

In my limited knowledge of JavaScript, I have come across an issue with the following code: function example() { document.getElementById("example").innerHTML = "<script>document.write(example)</script>"; } Unfortunately, this code doesn&ap ...

Potential issue with Jhipster: loading of data could be experiencing delays

I've encountered an issue with getting my chart to display properly. I am working on creating a chart using ng2-charts, where I retrieve data from a service and then display it on the chart. The problem arises when the data is not correctly displayed ...

"How can I make a dropdown open and close when a button is clicked, but also close when clicking outside of it at the same

One button click opens a dropdown, and it also closes when clicked outside. toggleAllCategories() { this.setState({ isOpenAllCategories: !this.state.isOpenAllCategories }); } The issue arises when attempting to open and close the dropdown by clic ...

loading preloaded fonts at the optimal moment

My webfonts are loaded using Webfontloader as shown below: <script src="//ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script> <script> WebFont.load({ custom: { families: ['BlenderProBook' ...

How can we capture the current row's value for later retrieval?

Using datatables to display data from a mySQL database, I am looking to extract the current row's value and present it in a modal for editing. This is how the data is integrated into Datatable: $(document).ready(function() { $(' ...

When a ng-model is added, the input value disappears

i am currently working on a form that contains angular values. <tr ng-repeat="alldata in c.da"> <td>{{alldata.id}}</td> <td><input type="text" class="form-control" value="{{alldata.name}}" ...

JSF CommandLink malfunctions on Firefox when reRendering an entire form

I am currently working on a JSF 1.2 application (Sun RI, Facelets, Richfaces) that was previously designed only for IE6 browsers. However, we now need to extend our support to include Firefox as well. On one of the pages, there is a form with a button tha ...

How can I generate codegen types using typeDefs?

I have been exploring the capabilities of graphql-codegen to automatically generate TypeScript types from my GraphQL type definitions. However, I encountered an issue where I received the following error message: Failed to load schema from code file " ...

Store the response data in a global variable or forward it to another function in Node.js using Express JS

I'm currently working on a function that makes a post request to an API (app.post), sending a token and a URL for redirection to webpay. The challenge I'm facing is saving that token in a global variable so that it can be accessed by another func ...

Is it possible to modify the location of my CSG object prior to performing subtraction in Threejs with ThreeCSG?

Looking to carve out specific "voids" in platforms using ThreeCSG. The goal is to have these voids positioned at particular locations on the larger platform. var geometry = new THREE.CubeGeometry( 500, 10, 500 ); var hole_geometry = new THREE.CubeGeom ...

Create a customized MUI select component with a label, all without the need for assigning an

One issue I am facing is with the Material UI React select component being used multiple times on a page. In the examples, all labeled selects use InputLabel with htmlFor that must match the id of the select. The challenge is that I cannot assign an id t ...

Conceal two DIV elements if one of them is empty

My slideshow has thumbnails connected to each slide. There are 10 DIVs representing the slides like this... <div class="SSSlide clip_frame grpelem slide" id="u751"><!-- image --> <?php while ($row = mysql_fetch_array($query ...

The response in Express.js effortlessly transforms keys from snake_case to camelCase

I am currently working on a small project within my organization, and we have an Express.js based node application running. This application sends a JSON response with keys in snake_case format. On the other hand, we have another node application that cons ...

Set my click event handler back to its default setting

I'm struggling with resetting a click function after it completes. How can I make sure it's ready to run again? $('body').on('click', '#ConfirmBet', function () { function randomImg() { var imgs = $(&apo ...

What is the best way to link JavaScript files from a Grails plugin in a separate Grails application?

I have developed a unique plugin that offers multiple Grails controllers and domain objects. Additionally, I have created several AngularJS UI components that I wish to utilize in various other projects. These specific files are located within the web-app ...

What are some of the techniques for customizing the DOM generated by material-ui in ReactJS?

Is there a way to style the dynamically created DOM elements from material-ui? I'm currently using GridListTileBar, which generates a DOM structure like this for its title property. <div class="MuiGridListTileBar-title-29" data-reactid=".0.3.0.$3 ...

Which Angular2 npm packages should I be installing?

When I'm trying to create an empty app without using angular-cli, it's really difficult for me to figure out which packages or libraries to include. Searching for angular2 on npmjs yields unwanted results, forcing me to click through multiple li ...

jQuery fieldset.change is a feature that allows you to manipulate

I'm looking to update the value of a button when a radio button is clicked. <fieldset id="product-color"> <input type="radio" id="red" name="color" value="Red"> <label for="red">Red</label><br> <input typ ...

Dropdown menu utilizing processing API and interacting with AJAX and DOM manipulation

My API data is not showing up in the dropdown menu. If I use ?act=showprovince, I can see the result. example.html <head> <link rel="stylesheet" type="text/css" href="css/normalize.css"> <link rel="stylesheet" type="text/css" hr ...