2

最近,我在我的公司中看到带有闭包函数的生产代码返回。比如return (function() {...}()); 我不喜欢看到这个,但我不是权威来源。我想我会问 StackOverflow 为什么以及何时使用这个好/坏。

* 笔记 *

假设您不担心名称空间污染,因为所有这些功能都已经在关闭中。

示例 1a:

function foo(bar) {
    return {
        x: 1 + bar,
        y: 1 - bar,
        duration: (function() {
            var i = 0,
                len = 5;
            var results = 0;

            for (; i < bar; i++) {
                results += 1 + (results * bar);
            }

            return results;
        }())
    };
}

示例 1b:

function barProcess(bar) {
    var i = 0;
    var len = 5;
    var results = 0;

    for (; i < bar; i++) {
         results += 1 + (results * bar);
    }

    return results;
}

function foo(bar) {
    return {
        x: 1 + bar,
        y: 1 - bar,
        duration: barProcess(bar)
    };
}

示例 1c:

function foo(bar) {
    var i = 0;
    var len = 5;
    var results = 0;

    for (; i < bar; i++) {
         results += 1 + (results * bar);
    }

    return {
        x: 1 + bar,
        y: 1 - bar,
        duration: results
    };
}

观察:

Example1a:
如果需要,内部函数会利用闭包。

示例 1b:
万一barProcess可能需要一些闭包,这可能会使参数列表很长并且难以维护。

Example1c:
每次调用没有额外的函数创建。最容易调试(在我看来)。

如果有人能给我一些技术原因,说明为什么应该使用示例 a、b 或 c,那将是非常棒的。


所以,我蹩脚的答案并没有让我满意,所以我尝试了这个。 JS 性能测试。我认为这让我的观察不会太远。

4

2 回答 2

0

I don't think its possible to choose a clear winner between examples a,b anc c for every simple case.

In the example you give, version (c) is good enough so I would go with it. That said, version (a) keeps the i, len and results veriables in an even tighter scope so it definitely could be a good way to go if you want to keep "x" and "y" more separate from duration "b".

I'm not a fan of splitting things into separate named functions just for organizational or scoping reasons, like you did on example (b), because it tends to make the code more complicated and harder to follow. However, if the barProccess is an actual reuseable abstraction that you can give a clear name for then keeping it separate might be a good idea.

Say your not concerned about namespace pollution because all of these functions are already in their on closure.

I think you are exagerating a bit here. The inner IFFE is not 100% recommended like the outer IFFE is but restricting scope even more is still perfectly OK and I don't think its worth fighting against your coleagues over it.

于 2013-05-17T22:28:11.187 回答
0

1a:foo()当内部函数执行时,外部函数没有返回,所以没有形成闭包。内部函数是一个匿名的“自执行”子程序。虽然一个自执行函数可以形成一个闭包,但这个函数既不需要也不需要。这是构建代码的一种稍微“华丽”的方式。

1b:没有形成闭包作为外部函数,foo()直接调用命名函数barProcess(),它返回一个数值,而不是一个函数。barProcess()如果还要从代码的其他地方调用,这种方法将很有用。

1c:没有形成闭合。foo()包含一个简单的代码块,它易于理解并且肯定会完成这项工作。由于 javascriptfor循环没有自己的范围,foo()将简化为:

function foo(bar) {
    for(var i=0, results=0; i<bar; i++) {
         results += 1 + (results * bar);
    }
    return {
        x: 1 + bar,
        y: 1 - bar,
        duration: results
    };
}
于 2013-05-18T05:22:32.667 回答