loveNoHate
loveNoHate

Reputation: 1547

Why are there no parentheses after a named function when you use .on('click' ) or .click()?

I just found out, that .on('click') and .click() require a named function to be written without parentheses behind.

Like so

$('.close').click(close);

Why is that so? I guess I want the function to happen right away on click, that's where you usally omit the parentheses, when assigning a function to a variable!?!

When you use an anonymous function, the parentheses have to be there!!

Upvotes: 0

Views: 1013

Answers (2)

Shai
Shai

Reputation: 7317

Because you want to pass the actual function as an argument (so jQuery can call it later, when the element is clicked), rather than calling the function and passing it's return value to the .click() (which isn't what you want, but is what would happen if you put the () after the function name).

Whatever function you pass as that first argument to .click() will be called when the element is clicked. It will always be called with one argument (the Event object, which you may or may not ignore depending on what needs to happen on click).

So you can do:

var close = function(evt) {
    // do stuff
};
$('.close').click(close);

Or

$('.close').click(function(evt) {
    // do stuff, anonymous function
});

Either way, you do NOT put () after it, because you do not want to call the function when you first apply it as the element's click handler. You want to let jQuery call it later on, when a click occurs. jQuery will do this by passing whatever arguments it wants (which we know will be 1 Event object).


To put it another way: the brackets immediately after the word function:

function(arg1, arg2)

always say what arguments you expect to receive.

The brackets after a function's name:

close(arg1, arg2)

would mean you want to call that function, passing in those arguments. This second one should never occur in this particular code, because you never call close. jQuery does (when the element is clicked).

Upvotes: 1

Quentin
Quentin

Reputation: 943510

Because the function is being passed as an argument.

If there were parentheses after it, it would be called and the return value would be passed as the argument.

I want the function to happen right away on click

"right away" and "on click" are two very different times.

When you use an anonymous function, the parentheses have to be there

The parentheses that form part of the function expression syntax do.

.click(function () { ... });

The ones that call the function must not.

.click(function () { ... }());

Upvotes: 2

Related Questions