javascriptfunctionpass-by-reference

Pass a parameter in a function which is passed by "reference" in another function


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.

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

Solution

  • 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/