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);
}
有帮助吗?

解决方案

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/

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top