Creating a variable with function parameters

How do I create a variable that stores the parameters of a function that can be called multiple times instead of repeating the same parameters when I want to call it? (The next example is not really a case where you want to store the parameters of a function, but in cases where you have several parameters of different lengths that can be used in different places, that would be very convenient).

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

+3


source to share


2 answers


Use .bind()

:

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

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

      



The first parameter .bind()

is the value that should be bound to this

when the function is called and what most people do with .bind()

. However, any additional arguments are passed as parameters.

You can still pass parameters with alerts1()

, and they will be third, fourth, fifth, etc. parameters.

+6


source


use closures, the returned inner function will have parameters associated with it. Plus it is cross browser, will work on older browsers without supportingbind

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

      



using

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

alert1()
alert2()

      

-2


source







All Articles