哪个Javascript功能放置更好?

Rst*_*voa 6 javascript parsing scope

我正在尝试构建一个游戏,我注意到对于组织而言,将一些函数放在其他函数中可能会更好,因为它们仅在原始函数中使用.例如:

function fn1()
{
    fn2();

    function fn2()
    {
        //Stuff happens here
    }
}
Run Code Online (Sandbox Code Playgroud)

fn1被多次fn1调用,并会fn2在执行中多次调用.何时fn1被调用,fn2每次都必须重新处理(缺少更好的词)?我因此而在性能方面输了吗?我应该把fn2之后fn1,而不是像这样?

function fn1()
{
    fn2();
}

function fn2()
{
    //Stuff happens here
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 2

您可以执行此操作来实现类似的范围,但仅创建 的一份副本fn2:

//Initiliaze before you call `fn1`:  
var fn1 = (function(){

    // This is the function assigned to fn1
    return function(){
        fn2();
    }

    function fn2()
    {
        //Stuff happens here
    }
})();
Run Code Online (Sandbox Code Playgroud)

将这些控制台输出与小提琴进行比较,前者创建了额外的 副本fn2,因为fn2每次调用都会创建本地范围fn1:http: //jsfiddle.net/A2UvC/3/和http://jsfiddle.net /A2UvC/3/

然而,额外的副本也有其优点fn2。他们可能有权访问不同的变量,例如在以下情况下:

function fn1(x){

    // Return an object exposing fn2 to the caller's scope
    return {fn2: fn2};

    // Each call to fn1 creates a new fn2 which has access 
    // to the closured `x` from the call to fn1 that created it
    function fn2(){
        console.log(x);
    }

}

var ex1 = fn1(1);
var ex2 = fn1(2);

ex1.fn2 == ex1.fn2; // true
ex1.fn2 == ex2.fn2; // false, because they are two distinct copies

ex1.fn2(); // 1
ex2.fn2(); // 2
ex2.fn2(); // 2
ex1.fn2(); // 1
Run Code Online (Sandbox Code Playgroud)