我正在尝试构建游戏,但我发现对于组织而言,将某些功能放在其他功能内可能会更好,因为它们专门用于原始功能中。例如:

function fn1()
{
    fn2();

    function fn2()
    {
        //Stuff happens here
    }
}
fn1被调用多次,并且fn1在执行过程中将多次调用fn2。调用fn1时,是否每次都要重新处理fn2(因为缺少更好的词)?我是否因此而失去表现?我应该这样将fn2放在fn1之后吗?
function fn1()
{
    fn2();
}

function fn2()
{
    //Stuff happens here
}

最佳答案

您可以执行此操作以实现类似的作用域,但只能创建fn2的一个副本:

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

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

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

将它们的控制台输出与 fiddle 进行比较, fiddle 的前者创建了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

关于javascript - 哪个Javascript函数放置更好?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18450715/

10-11 14:45