Sohaib Farooqi Sohaib Farooqi - 6 months ago 11
Javascript Question

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?

Answer

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