Scrabby McDooby
Scrabby McDooby

Reputation: 57

jQuery- how .click() works with function identifier passed as argument?

$('button').click(function(){ console.log('works'); });

This outputs 'works' when I click the required button.

But if I pack the same code in a function and call it with parentheses attached to it(as you usually invoke a function), as in

function worker(){ console.log('works'); }
$('button').click(worker());

worker gets fired without any click on button. But if I avoid the parentheses, as in

function worker(){ console.log('works'); }
$('button').click(worker);

I'm getting the desired functionality. Why the click handler behaves this way?

Upvotes: 1

Views: 37

Answers (2)

Evan Bechtol
Evan Bechtol

Reputation: 2865

When you call a function in JavaScript without parenthesis, what you are doing is assigning the actual function. This does not immediately execute the function.

When you call a function in JavaScript with parenthesis, you are executing the function immediately and returning the value of that function.

Having said that, if you had a function that returned a function itself, you could in-fact call a function, whose return value would then be another function. (Generally not advised)

To address your comment: Suppose you write the following statement: $('button').click(console.log('works')); The result would be that as soon as your page is loaded, "works" will be printed to the console. This is because console.log() is a function being called with parenthesis.

However, if you did the following approach:

var worksFunc = function() {console.log('works')};
$('button').click(worksFunc);

It will now reference the function for execution on the click event.

DEMO

Upvotes: 1

eisbehr
eisbehr

Reputation: 12452

You didn't pass the function object with worker(), the brackets let it execut directly. Removing the brackes will let you pass the reference to the function by the name worker.

Maybe it is clearer if you look at it this way:

var worker = function() { console.log('works'); }
$('button').click(worker);

Upvotes: 1

Related Questions