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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With