Delirium tremens
Delirium tremens

Reputation: 4739

How do you know you have to use function() {}?

code 1

$(document).ready(function() {
    $('.poem-stanza').addClass('highlight');
});

code 2

$(document).ready(
    $('.poem-stanza').addClass('highlight');
);

Upvotes: 1

Views: 221

Answers (5)

Guffa
Guffa

Reputation: 700562

If you need a callback function, you use the function keyword. When you use methods like ready and click, you don't want the code to run when you set up the event, but when the event happens, so you need a callback function.

Using an anonymous function is just like using a named function that you defined earlier. In an example like this it's easier to follow what's happening:

function onReady() {
    $('.poem-stanza').addClass('highlight');
}

$(document).ready(onReady);

Upvotes: 0

Tim Büthe
Tim Büthe

Reputation: 63764

Like the other guys said, you have to look up the documentation to see, what type of parameters the function accepts. However, the important part here is this: If you have a statement, it gets execute when the interpreter come across it. If you define a function and pass it to the ready function, the ready function decides when to execute it. In this particular case, when the document is ready. Another example is setTimeout which expects a function and a number of milliseconds as parameters.

The rule is this: When you want to pass some code to some other function, you have to wrap it in a function. If you use a (unwrapped) statement, it will be executed and the result is passed to the function.

Upvotes: 0

usoban
usoban

Reputation: 5478

Heh, that's how it is :D

No, seriously, when you have to do something inside ready(); or similar methods, you use an. function. Other methods accept parameters. Docs will provide you with details.

Upvotes: 0

Philippe Leybaert
Philippe Leybaert

Reputation: 171864

If the function accepts a function as a parameter, code 2 will not work, because

$('.poem-stanza').addClass('highlight');

is not a function definition (it's a statement)

To create an object that represents a function, one of the following syntaxes should be used:

function myFunc() {
}

or

var myFunc = function() {
}

or

var myFunc = new Function("...javascript code...");

After one of the definitions above, myFunc will hold an object representing a function.

Upvotes: 0

Quentin
Quentin

Reputation: 943981

You read the documentation for the method you are calling (the ready method in this case) and see what sort of value it expects.

If it expects a function, use your first example.

If it expects a jQuery* object, use your second example (since the return value from the addClass method is a jQuery object).

*I assume you are using jQuery as I think it is the only library that has functions named like that. I could be wrong though, $ is a stupid name for a function.

Upvotes: 3

Related Questions