哪个Javascript功能放置更好?

时间:2013-08-26 18:36:21

标签: javascript parsing scope

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

function fn1()
{
    fn2();

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

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

function fn1()
{
    fn2();
}

function fn2()
{
    //Stuff happens here
}

1 个答案:

答案 0 :(得分: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的额外副本,因为为fn2的每次调用创建了一个本地范围的fn1:{{ 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