Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a variable with function parameters

How can I create a variable that stores function parameters that can be called multiple times instead of having to repeat the same parameters when I want to invoke it? (The following example isn't really a case where you would want to store function parameters, but in cases where you have multiple parameters of varying lengths that may get used in multiple places, it would be very handy).

function showAlerts(alert1,alert2) {
    console.log(alert1 + '\n' + alert2);
}

// I would like to be able to define a variable that can be called later
// doing it this way (obviously) just runs the function immediately
var alerts1 = showAlerts('test1','test2');
var alerts2 = [showAlerts('test3','test4')];
var alerts3 = ['test5','test6'];

if(0===1) {
  alerts1; 
} else if(1===0) {
  alerts2;
} else {
  showAlerts(alerts3);
}

http://jsbin.com/cenili/1/edit?html,js,console

like image 751
Realto619 Avatar asked Dec 13 '25 09:12

Realto619


1 Answers

Use .bind():

var alerts1 = showAlerts.bind(undefined, "test1", "test2");

alerts1(); // note the () which are still necessary to call the function

The first parameter to .bind() is the value to be bound to this when the function is called, and that's what most people do with .bind(). However any additional arguments are passed along as parameters.

You can still pass parameters with alerts1(), and they'd be the third, fourth, fifth, etc. parameters.

like image 107
Pointy Avatar answered Dec 16 '25 05:12

Pointy