0

Okay, this is kind of hard to explain, but I have created a fiddle here to demonstrate what I am trying to accomplish.

I think this is related to How can I pre-set arguments in JavaScript function call? (Partial Function Application), but I am failing to figure out how to apply the method mentioned in this post to my scenario.

I have three functions.

  • func1. A function that is passed to and gets called by func2 once func2 is done doing its business.
  • func2. The function that receives as a parameter the function (func1) it is going to call.
  • func3. The function that calls func2.

I want to pass a parameter to func3 that gets passed to func1 in func2.

Ex:

<input type='button' id='testButton' onclick='func3()' value='Click Me' />
<input type='button' id='testButton2' onclick='func3a(true)' value='Click Me Also' />

func3 = function (aBool) {
        func2(func1);
    }

// I want to be able to pass a parameter to the function 
// that gets called in func2 
func3a = function (aBool) {
    func2(func1(aBool));
}

func1 = function (data, myBool) {
    alert(data[0] + ' ' + myBool);
}


// Cannot Change this function 
func2 = function (func) {
    var data = [];
    data[0] = "Hello World"
    func(data);
}
Community
  • 1
  • 1
Popo
  • 2,402
  • 5
  • 33
  • 55

2 Answers2

2

You could wrap the function passed to func2 with an inline function. Which then delegates the call to func1 passing the additional parameter.

E.g.:

function func3a(aBool) {
  func2(function(data) {
    func1(data, aBool);
  });
}

http://jsbin.com/qamigura/1/

Yoshi
  • 54,081
  • 14
  • 89
  • 103
  • Thanks, this works in both my example and actual code. I have been watching some of Crockford's videos on youtube recently, and I knew I had seen this somewhere. Just was not putting my finger on it. – Popo Mar 26 '14 at 15:48
2

You can use Function.prototype.bind to bind not only the context the function executes in (this), but also the first parameters the function gets called with.

func3 = function (aBool) {
    func2(func1.bind(null,aBool));
}


func1 = function(myBool, data) {
    alert(data[0] + ' ' + myBool);
}

Note that i had to change the signature of func1 to get the boolean as the first parameter so func2 can set the second parameter when it calls it.

The implementation of bind is similar to Yoshi's answer in practice. Note that his answer doesn't impose any limitation on the order of parameters.

Tibos
  • 27,507
  • 4
  • 50
  • 64
  • Thanks, I will work through your answer as well, I want to understand how this works. Although, this may be more difficult to implement as my actual code has many more parameters. – Popo Mar 26 '14 at 15:50
  • I just wanted to post this here because bind was intended exactly for partial function application. It is more limited, but it's also easier to write, so you should use it whenever it fits. – Tibos Mar 26 '14 at 15:58