I want to push functions with params to an array without getting them executed. Here is what i have tried so far:
var load_helpers = require('../helpers/agentHelper/loadFunctions.js');
var load_functions = [];
load_functions.push(load_helpers.loadAgentListings(callback , agent_ids));
load_functions.push(load_helpers.loadAgentCount(callback , agent_data));
But in this way functions gets executed while pushing. This Question provides similar example but without params. How can I include params in this example?
The simple answer is yes you can place function in an array. In fact, can declare variables and reference them in your function.
Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.
Typically, when you want to execute a function on every element of an array, you use a for loop statement. JavaScript Array provides the forEach() method that allows you to run a function on every element. The forEach() method iterates over elements in an array and executes a predefined function once per element.
You have to bind the parameters to the function. The first parameter is the 'thisArg'.
function MyFunction(param1, param2){
console.log('Param1:', param1, 'Param2:', param2)
}
var load_functions = [];
load_functions.push(MyFunction.bind(undefined, 1, 2));
load_functions[0](); // Param1: 1 Param2: 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With