Samantha J T Star
Samantha J T Star

Reputation: 32828

Do I have to define a js function before another function uses it if they are both enclosed in another function?

I have the following code:

    doAjax = function () {
        $.ajax({
            cache: false,
            url: url,
            dataType: 'html'
        })
        .done(onDone)
        .fail(onFail)
        .always(function () {
            ;
        });
    },
    onDone = function (data) {
        content = data;
        if (content.match(/^[eE]rror/)) {
            mvcOnFailure(content);
        } else {

I am getting errors with jslint saying things like "onDone" is used before it is defined. Is this something I should try to avoid, is this a problem. Note that both the doAjax and onDone functions are both enclosed inside another function.

Upvotes: 0

Views: 231

Answers (1)

jfriend00
jfriend00

Reputation: 707766

If you define it like:

function onDone() {}

Then, you do not have to define it before you use it in the same scope because all function definitions like this are automatically "hoisted" to the top of the function and are defined before any code in that scope runs.

If you define it like:

onDone = function() {}

then, javascript respects the order you run your code and onDone does not have this value until that line of code is executed in the normal flow of of code execution in your function so this line would need to be executed before anything that uses onDone is called.

Upvotes: 2

Related Questions