2

I have defined a global variable ff and then call f1 to assign function f3 to it. When I call f2, f3 will running.

var ff;
function f1() { ff=f3; }
function f2() { ff(); }
function f3() { alert("hello"); }

but if f3 take a parameter as following

function f3(txt) { alert(txt); }

and I call f1 to assign ff as following

function f1() { ff=f3("hello"); }

f3 will run at the same time.

I don't want f3 running when I assign it to ff and I need pass a argument. How can I achieve this? A variable with () after it as if will make it a function and make it run.

3 Answers 3

13

Try using bind:

ff = f3.bind(null, "hello")

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

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

Comments

1

You are assigning ff the value of the f3 call, in your second example, which is why it calls your function. You should make the assignment ff=f3, as you did initially. Then you can call ff with a parameter: ff("hello")

1 Comment

I may assign f4 which takes different numbers of parameters to ff in f1 according to different condition. So I can not call ff with a parameter in f2.
0

What about this?

var ff;
function f1() { ff=f3; }
function f2() { ff('hello'); }
function f3(text) { alert(text); }

1 Comment

Please add some comments about your solution on why and how it solves the problem

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.