Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Functions with params to Array Javascript (Node.js)

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?

like image 521
Sohaib Farooqi Avatar asked May 30 '16 07:05

Sohaib Farooqi


People also ask

Can you put functions in an array JavaScript?

The simple answer is yes you can place function in an array. In fact, can declare variables and reference them in your function.

How do you pass an array as a function argument in JavaScript?

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.

How do you call a function inside an array?

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.


1 Answers

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
like image 144
KMathmann Avatar answered Oct 06 '22 00:10

KMathmann