4

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);

2 Answers 2

8

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, can't believe the solution was this easy. Thanks so much!
2
talk('John', hello, weather.bind(null, 'sunny'), goodbye);

In this case .bind is essentially returning a function with some bound parameters - quite analogous to Arun's answer, though you may consider this method a little more succinct / readable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.