【问题标题】:Function definition inside function [duplicate]函数内部的函数定义[重复]
【发布时间】:2013-07-16 07:52:31
【问题描述】:

如果我有代码:

function A() {

  function B() {

  }

  B();

}

A();
A();

每次调用 A 时是否都会解析和创建 B 函数(这样会降低 A 的性能)?

【问题讨论】:

  • 你为什么需要那个? :)
  • 我会说是的,因为函数 B 只存在于函数 A 的范围内
  • 为什么不在 A 之外创建函数 B,在 A 内部调用 B?
  • Gintas K:我有函数,该函数中的一些代码块需要重用,但只是在那个函数中
  • 我想其他人已经问过同样的问题了:stackoverflow.com/questions/6476540/…

标签: javascript


【解决方案1】:

如果你只想在内部使用函数,那么闭包怎么样。这里举个例子

    var A = (function () {
    var publicFun = function () { console.log("I'm public"); }
    var privateFun2 = function () { console.log("I'm private"); }

    console.log("call from the inside");
    publicFun();
    privateFun2();

    return {
        publicFun: publicFun
    }
})();   

console.log("call from the outside");
A.publicFun();
A.privateFun(); //error, because this function unavailable

【讨论】:

    【解决方案2】:
    function A(){
    
        function B(){
    
        }
        var F=function(){
            B();
         }
         return F;
    }
    var X=A();
    //Now when u want to use this  just use this X function it will work without parsing B() 
    

    【讨论】:

      猜你喜欢
      • 2011-09-18
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 2018-05-12
      • 2017-01-21
      • 1970-01-01
      相关资源
      最近更新 更多