6

我正在尝试构建一个游戏,我注意到对于组织来说,将一些功能放在其他功能中可能会更好,因为它们专门用于原始功能。例如:

function fn1()
{
    fn2();

    function fn2()
    {
        //Stuff happens here
    }
}

fn1被多次调用,并在执行过程中多次fn1调用。fn2何时fn1调用,是否fn2每次都必须重新处理(因为没有更好的词)?我是否因此而在性能方面输了?我应该像这样放在fn2后面吗?fn1

function fn1()
{
    fn2();
}

function fn2()
{
    //Stuff happens here
}
4

1 回答 1

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
    }
})();

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

然而,额外的副本也有优势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
于 2013-08-26T18:40:16.747 回答