Realto619
Realto619

Reputation: 301

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

Upvotes: 3

Views: 103

Answers (2)

user2727195
user2727195

Reputation: 7340

use closures, the internal function getting returned will have parameters bound to it. Plus it's cross browser, will work in older browsers not supporting bind

function getShowAlertsFunc() {
    var args = arguments
    return function() {
        for(var i=0; i<args.length; i++) {
            console.log(args[i]);   
        }
    }
}

usage

var alert1 = getShowAlertsFunc("john", "doe")
var alert2 = getShowAlertsFunc("jane", "doe")
var alert3 = getShowAlertsFunc("test", "abc", "123")

alert1()
alert2()

Upvotes: -2

Pointy
Pointy

Reputation: 414086

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.

Upvotes: 6

Related Questions