简体   繁体   中英

JavaScript: Getting rid of three JSHint errors

Please find below a snippet of my Node.JS server code:

// Define the user API
var API = {
    list: 'private',
    login: 'public',
    logout: 'private',
    add: 'admin',
    remove: 'admin',
    edit: 'admin'
};

// Attach API handlers
for(var label in API) {
    var denied = 'Permission denied';

    var wrapper = (function (label) {
        return function (req, res) {
            var permission = API[label];

            if(!req.session) {
                if(permission !== 'public') {
                    res.send(denied);
                    return;
                }
            } else if((permission === 'admin') && (req.session.rights !== 'Administrator')) {
                res.send(denied);
                return;
            }

            eval(label + '(req, res)');
        };
    }(label));

    server.post('/user/' + label, wrapper);
}

Basically, I have an API handler for each property in API , and I attach the handlers programmatically, dealing with permissions as appropriate. JSHint however really does not like this. I get three errors:

Line 29: eval(label + '(req, res)');
eval is evil.

Line 31: }(label));
Don't make functions within a loop.

Line 12: for(var label in API) {
The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.

How can this piece of code be improved to make JSHint happy? Are there other changes you would suggest to the code?

I would recommend going through the options that make jslint less strict and setting these ( provided you understand the why ). Jslint is very strict and that is why it has options to make it less strict. The important thing is that you know why they were flagged and why it is OK ok for you to allow these things.

For example to allow eval use:

/*jslint evil: true */

Some use:

/*jslint plusplus: true */

as they find that ++ and -- cause them no problems with bug creation or readability.

jslint is used to bring attention to POTENTIAL pitfalls. If you understand them, you can go around them.

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