How to add parameters to a function passed as a paramter?

S

Steve Neill

Here's an interesting problem...

I have 2 functions, aFunc() and bFunc(). I call aFunc() passing a call
to bFunc() as a parameter. Function aFunc() executes bFunc(). Function
bFunc() lists the parameter values passed to it.

OK, here's the twist...

I want to add some parameters to bFunc() from inside aFunc(). Can that
be done?

Sorry no prizes, except the satisfaction of the solution :)

Regards,
Steve


aFunc(function() { bFunc(); } );

function aFunc(f) {
var x = 1;
var y = 2;

// add x, y as parameters to function f()
// ???

// execute the parameter function
f();
}

function bFunc() {
for (var i = 0; i < arguments.length; ++i) {
alert(arguments);
}
}
 
M

Michael Winter

I have 2 functions, aFunc() and bFunc(). I call aFunc() passing a call
to bFunc() as a parameter. Function aFunc() executes bFunc(). Function
bFunc() lists the parameter values passed to it.

OK, here's the twist...

I want to add some parameters to bFunc() from inside aFunc(). Can that
be done?

Yes, but your call to aFunc needs to be changed.

Functions are objects, and just like all other objects, you can refer to
them with any number of identifiers. Consider:

function myFunction() {
}

var yourFunction = myFunction;

You can now invoke myFunction with either myFunction() or yourFunction()
with exactly the same results. For your particular case, this would become:

function aFunc(f) {
var x = 1,
y = 2;

f(x, y); // Call bFunc with arguments x and y.
}

function bFunc() {
for(var i = 0, n = arguments.length; i < n; ++i) {
alert(arguments);
}
}

aFunc(bFunc); // Note: no parentheses on bFunc!

Hope that helps,
Mike
 
B

Bob Gregory

Here's an interesting problem...
<snip />

Am I missing something?

aFunc(bFunc);

function aFunc(f) {
var x = 1;
var y = 2;

// add x, y as parameters to function f()
// ???

// execute the parameter function
f(x,y);
}

function bFunc() {
for (var i = 0; i < bFunc.arguments.length; ++i) {
alert(bFunc.arguments);
}
}
 
M

Michael Winter

[snip]
Am I missing something?

Not especially, but...

[snip]
function bFunc() {
for (var i = 0; i < bFunc.arguments.length; ++i) {
alert(bFunc.arguments);
}
}


....the arguments object is not a property of the function, but of the
function's activation object. Effectively, it is a local variable to
accessed like all other local variables.

Mike
 
S

Steve Neill

Thank you Michael. I didn't realize I could pass a function that way
(now I do!) This solves the problem -- Thank you
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top