如何修复jslint错误'不要在循环中创建函数'。 [英] How to fix jslint error 'Don't make functions within a loop.'?

查看:117
本文介绍了如何修复jslint错误'不要在循环中创建函数'。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力让我们所有的JS代码都通过jslint进行传递,有时需要通过大量的调整来获取遗留代码的选项,以便稍后正确修复它。

I am working on making all of our JS code pass through jslint, sometimes with a lot of tweaking with the options to get legacy code pass for now on with the intention to fix it properly later.

jslint有一件事抱怨我没有工作。这就是当使用这样的结构时,我们得到错误'不要在循环中使函数。'

There is one thing that jslint complains about that I do not have a workround for. That is when using constructs like this, we get the error 'Don't make functions within a loop.'

for (prop in newObject) {
    // Check if we're overwriting an existing function
    if (typeof newObject[prop] === "function" && typeof _super[prop] === "function" &&
        fnTest.test(newObject[prop])) {
        prototype[prop] = (function(name, func) {
            return function() {
                var result, old_super;

                old_super = this._super;
                this._super = _super[name];
                result = func.apply(this, arguments);
                this._super = old_super;

                return result;
            };
        })(prop, newObject[prop]);
    }
}

此循环是经典继承的JS实现的一部分扩展现有类的类在调用扩展类的成员时保留扩展类的超级属性。
为了澄清,上面的实现受到了这个博客文章的启发。 John Resig。

This loop is part of a JS implementation of classical inheritance where classes that extend existing classes retain the super property of the extended class when invoking a member of the extended class. Just to clarify, the implementation above is inspired by this blog post by John Resig.

但我们还在循环中创建了其他函数实例。

But we also have other instances of functions created within a loop.

唯一的解决方法是远程是从jslint中排除这些JS文件,但我们希望使用jslint进行代码验证和语法检查,作为我们持续集成和构建工作流程的一部分。

The only workaround so far is to exclude these JS files from jslint, but we would like to use jslint for code validation and syntax checking as part of our continuous integration and build workflow.

是否存在一个更好的方法来实现这样的功能,还是有办法通过jslint调整这样的代码?

Is there a better way to implement functionality like this or is there a way to tweak code like this through jslint?

推荐答案

Douglas Crockford有一个实现上述的新惯用方法 - 他的旧技术是使用内部函数来绑定变量,但新技术使用函数制作器。请参阅幻灯片中的幻灯片74到他的功能终极讲座。 [此幻灯片不再存在]

Douglas Crockford has a new idiomatic way of achieving the above - his old technique was to use an inner function to bind the variables, but the new technique uses a function maker. See slide 74 in the slides to his "Function the Ultimate" talk. [This slideshare no longer exists]

对于懒惰,这里是代码:

For the lazy, here is the code:

function make_handler(div_id) {
    return function () {
        alert(div_id);
    };
}
for (i ...) {
    div_id = divs[i].id;
    divs[i].onclick = make_handler(div_id);
}

这篇关于如何修复jslint错误'不要在循环中创建函数'。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆