简体   繁体   中英

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.

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.

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