1

I'm working on a function that is too complicated (processor) so I embedded part of the functionality in a nested "utility function" inside it (print). A simplified version of it looks like this:

var out = document.getElementById( "output" );

function processor ( n ) {
    function print( msg ) {
        out.innerHTML  += msg;
    }
    while ( n > 0 ) {
        print( n-- );
        print( ", " );
    }
    print( "<br/>" );
}

for ( var i = 0; i < 10; i++ ) {
    processor( i );
}

You can see it in action in this JSfiddle.

The question is: am I really creating 10 instances of the utility function print()? If yes, what is a more efficient way to write this code without putting the utility function outside the processor() function? I want the print() function to only be accessible in processor() and nowhere else. One solution is namespace.

I've read this question and even though it's related but it's not directly my answer: Efficiency of creating an event handler in a nested loop: am I creating 1440 functions here?

4

2 回答 2

3

用 JavaScript 术语来说,的。然而,实际上,JavaScript 引擎本身很可能会重用定义函数的代码,并适当调整范围以供重用。我已经阅读了Chromium 中使用的这种方法。

要仅使 print 功能可在 中访问processor(),您必须创建一个 IIFE:

var out = document.getElementById( "output" );

var processor = (function () { 
    function print( msg ) {
        out.innerHTML  += msg;
    }

    return function ( n ) {
        while ( n > 0 ) {
            print( n-- );
            print( ", " );
        }
        print( "<br/>" );
    };

}());

for ( var i = 0; i < 10; i++ ) {
    processor( i );
}

您在这里而不是在循环中重新创建函数的原因是因为 a function(eg processor) 定义了一个新范围,而块(循环等)没有;函数声明被提升到作用域的顶部,而不是

于 2012-07-02T12:50:17.517 回答
1

简而言之,是的,你是。但是由于它们都是函数本地的,所以它们会在函数返回时从堆栈中弹出并销毁。由于您processor()在 for 循环中串行调用该函数,因此该函数的实例只有一次print()有效并可在任何时间点访问。

于 2012-07-02T12:52:01.387 回答