简体   繁体   中英

Use a function with parameters inside a callback

I've written a function which may take an unknown number of functions as parameters, but can't figure how I can make this work when one or more of the functions take parameters too.

Here is a quick example of what I would like to achieve:

function talk(name) {
  console.log('My name is ' + name);
  var callbacks = [].slice.call(arguments, 1);
  callbacks.forEach(function(callback) {
    callback();
  });
}

function hello() {
  console.log('Hello guys');
}

function weather(meteo) {
  console.log('The weather is ' + meteo);
}

function goodbye() {
  console.log('Goodbye');
}

// I would like to be able to do the following:
//talk('John', hello, weather('sunny'), goodbye);

You can pass an anonymous function which can call the function with required parameters

talk('John', hello, function(){
    weather('sunny')
}, goodbye);

 function talk(name) { console.log('My name is ' + name); var callbacks = [].slice.call(arguments, 1); callbacks.forEach(function(callback) { callback(); }); } function hello() { console.log('Hello guys'); } function weather(meteo) { console.log('The weather is ' + meteo); } function goodbye() { console.log('Goodbye'); } talk('John', hello, function() { weather('sunny') }, goodbye); 

talk('John', hello, weather.bind(null, 'sunny'), goodbye);

在这种情况下, .bind本质上是返回一个带有一些绑定参数的函数 - 非常类似于Arun的答案,尽管你可能会认为这种方法更简洁/可读。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM