Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript assign a function to a variable without running it

Tags:

javascript

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.

like image 245
LING Avatar asked Aug 11 '26 17:08

LING


2 Answers

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.

like image 137
CD.. Avatar answered Aug 13 '26 08:08

CD..


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")

like image 25
Andreas Avatar answered Aug 13 '26 07:08

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!