使用函数参数创建变量

Rea*_*619 3 javascript function

如何创建一个存储可以多次调用的函数参数的变量,而不是在我想调用它时重复相同的参数?(以下示例实际上并不是您希望存储函数参数的情况,但是如果您有多个不同长度的参数可能会在多个位置使用,那么它将非常方便).

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);
}
Run Code Online (Sandbox Code Playgroud)

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

Poi*_*nty 6

用途.bind():

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

alerts1(); // note the () which are still necessary to call the function
Run Code Online (Sandbox Code Playgroud)

第一个参数是调用函数时.bind()要绑定的值this,这是大多数人所做的事情.bind().但是,任何其他参数都作为参数传递.

你仍然可以传递参数alerts1(),它们是第三,第四,第五等参数.