简体   繁体   中英

js difference between foo(), foo and function(){foo()}

I have a jquery dialog with a button on it (my button, not one of the dialog buttons).

After the dialog is set up I have the following bit of code:

$('#bar').click(foo('baz'));

When I load the page and make the dialog appear, foo is run(without pressing #bar).

If the code is:

$('#bar').click(foo);

or

$('#bar').click(function(){foo('baz')});

foo doesn't run.

Why is that? Pointers to where I should RTFM, gratefully received.

Just to clarify: Why does foo run in the first instance without the button being pressed (ie upon dialog initialisation) and foo not run in the latter 2 examples.

Oh, I think I just worked it out.

In 1. the result of foo is being passed to click. In 2. I'm still not sure. In 3. The anon function is being passed to click.

This doesn't wait for the click to call foo :

$('#bar').click(foo('baz'));

( foo('baz') is executed when this line is executed, not when the user click #bar )

This doesn't pass the argument to foo :

$('#bar').click(foo);

This is probably what you need (unless foo builds and returns a function, which I guess it doesn't) :

$('#bar').click(function(){foo('baz')});

The fact it doesn't work may be that your element with id bar isn't found or you don't click it.


Detailed explanation :

When you execute

foo(bar); 

you execute foo with argument bar .

Wen you execute

a = foo;

you give to the variable a the value foo , which may be a function or not.

When you call

var a = function() {foo(bar)};

you create a new anonymous function, which executes foo(bar) when called, and you gives this new function as value of the variable a .

When you execute

$('#bar').click(function(){foo('baz')});

you pass a new function, calling foo('baz') when called, as argument to $('#bar').click( . JQuery calls this function when you click the element with id bar .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM