简体   繁体   中英

Mutual recursion and JSLint - function was used before it was defined

If I write the following code, JSLint complains that 'isOdd' was used before it was defined . Is there a way to write mutually recursive code and still please JSLint?

var isEven = function(n) {
    if (n === 0) {
        return true;
    }
    return isOdd(n - 1);
};

var isOdd = function(n) {
    if (n === 0) {
        return false;
    }
    return isEven(n - 1);
};

For JSLint, you have to add a global variables directive to the top of the file, so that it ignores usage of temporary "undefined" functions and variables.

/*global isOdd */

var isEven = function(n) {
    if (n === 0) {
        return true;
    }
    return isOdd(n - 1);
};

var isOdd = function(n) {
    if (n === 0) {
        return false;
    }
    return isEven(n - 1);
};

You could also declare isOdd at the top, but then you would change your actual code because a linting program doesn't understand hoisting:

var isOdd;

var isEven = function(n) {
    if (n === 0) {
        return true;
    }
    return isOdd(n - 1);
};

isOdd = function(n) {
    if (n === 0) {
        return false;
    }
    return isEven(n - 1);
};

Converting these functions to methods of an object quell the error message from JSLint. This also does a better job of keeping the global namespace less polluted.

var numUtil = {
    isEven: function(n) {
        if (n === 0) {
            return true;
        }
        return this.isOdd(n - 1);
    },
    isOdd: function(n) {
        if (n === 0) {
            return false;
        }
        return this.isEven(n - 1);
    }
};

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