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

Get started by setting up and utilizing react version 0.14.0 on your

I'm currently facing an issue in my project while using react-0.14.0. The error message I'm encountering is: Invariant Violation: ReactDOM.render(): Invalid component element. This may be caused by unintentionally loading two independent copie ...

What is the best way to verify the existence of an email address?

I'm currently using the jQuery validation plugin and everything is working fine, but I've hit a snag when it comes to checking email addresses. The issue is that the plugin returns either true or false based on whether the email exists or not. Ho ...

Tips for enhancing undo/redo functionality when working with canvas drawings in React

Currently, I am working on implementing undo/redo functionality for html-canvas drawing on medical (.nii) images in a React application. The images consist of slices stored in a Uint8ClampedArray and usually have dimensions around 500 (cols) x 500 (rows) x ...

What could be causing the recurring appearance of the success alert message in an AJAX call to a PHP script in this particular situation?

Below you will find two code blocks, each designed to handle an AJAX call to a PHP file upon clicking on a specific hyperlink: <script language="javascript" type="text/javascript"> $(".fixed").click(function(e) { var action_url1 = $(th ...

Load as soon as the browser is launched

I have developed a unique button that utilizes JavaScript to display the server status through an API. However, I am facing an issue where the server status does not automatically load when the browser is opened for the first time. You need to manually cli ...

Having trouble getting the .replace() Javascript function to work on mobile devices?

I have a code snippet for implementing Google Analytics. Here it is: $(function () { $('.plan-choose-btn a').bind('click', function(e) { //ga load image <% String myaccGAEventUrl = trackGoogleAnalyticsEvent(requ ...

Information is inaccessible beyond onBeforeMount in the Composition API of Vue 3

In my code snippet block, I have the following code: <script setup lang="ts"> import ApiService from '../service/api' import { reactive, onBeforeMount } from 'vue' let pokemons = reactive([]) onBeforeMount(async ()=> ...

Is it necessary to use asynchronous actions in Node.js only when developing server applications?

In the Node.js application I'm developing, there is a piece of code similar to this within an async function: await a(param1); await b(param2); await c(param3); await d(param4); From my understanding, this setup works well for a server-based app. Fo ...

How to create a continuous loop for a JavaScript carousel

I have a simple carousel set up with this code. I'm looking to make it loop back to the beginning after reaching the third quote-item. Can anyone provide some guidance? Thank you! This is the JavaScript used: <script> show() $(functi ...

Creating a drop-down menu that aligns perfectly under the bar in Material-UI: What you need to know

While working with Material-UI, I encountered a problem with my drop-down menu. Every time I click on it, it covers the bar instead of appearing below it (see image links below). https://i.stack.imgur.com/1Y8CL.jpg https://i.stack.imgur.com/emf87.jpg Is ...

Showing the computation outcome on the identical page

I have implemented a table within my PHP code. In the second column of this table, it typically displays "---". However, once I click the submit button, the same page should now display the calculated result. Here is an example: <table> <tr>& ...

Angular is reporting that the check-in component is nonexistent

I encountered an error in my Angular 8 application while working on a component. The error seems to be related to nested components within the main component. It appears that if the component is empty, the error will be shown, but if it's not null, th ...

Using Moment.js to showcase historical information within a specified timeframe based on the user's timezone

I'm finding it challenging to properly handle historical data display: Current Situation: The database contains records stored in "YYYY-MM-DD HH:mm:ss" format in UTC+0 (MariaDB - DateTime type) A web application (using moment.js) allows users to se ...

``req.body is not being properly populated when data is sent using form-data, causing

When I send data in my Node.js application as raw JSON/x-www-form-urlencoded from Postman, it gets passed successfully. However, when sending the data as form-data from either Postman or my Angular frontend, the req.body is coming back as undefined. I have ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

How can I fix the issue of clearInterval not functioning properly in an Electron JS application?

The clearInterval function is not working properly in this code. What can be done to fix this issue? var inter; ipcMain.on("start-stop",(err,data)=>{ console.log(data.data) function start(){ inter = setInterval(fu ...

Attempting to coordinate a virtual meeting through the utilization of the Zoom API

I'm currently in the process of developing a website using Node.js, Express.js, and Mongodb. One feature I am working on is the ability for users to schedule Zoom meetings directly within the website. The desired functionality would be for users to sc ...

Pass the object either in JSON format or as a variable using the drag and drop feature

Here's a quick question: when using the Drag and Drop system, I'm not sure which method is better. Is it more efficient to : utilize setData and getData to transfer a JavaScript object? (Utilizing JSON conversion since setData only passes st ...

Executing a Particular Function in PHP with Arguments

As a newcomer to PHP and JavaScript, I'm attempting to invoke a specific function in a PHP file from JavaScript. Here is my code: <script> function load($dID) { $.ajax({ url: "myPHP.php", ...

How can one effectively overcome the constraint in HTML5 canvas that prevents altering the positions of previously sketched elements?

I am currently working on creating a wind map that displays data from seven different weather stations. My goal is to develop a fluid and interactive map similar to the ones found in this animation or this animation. In my research, I came across an artic ...