简体   繁体   English

JavaScript:摆脱三个JSHint错误

[英]JavaScript: Getting rid of three JSHint errors

Please find below a snippet of my Node.JS server code: 请在下面找到我的Node.JS服务器代码的片段:

// 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. 基本上,我对每个财产API处理器API ,并且附上了处理程序,处理权限适当。 JSHint however really does not like this. 但是JSHint确实不喜欢这样。 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? 如何改进这段代码以使JSHint满意? 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不太严格的选项并进行设置(只要您理解了为什么)。 Jslint is very strict and that is why it has options to make it less strict. Jslint非常严格,这就是为什么它可以选择使其不严格。 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. jslint用于引起对潜在陷阱的关注。 If you understand them, you can go around them. 如果您了解它们,则可以绕开它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM