How do you call a local function?

前端 未结 3 747
失恋的感觉
失恋的感觉 2021-01-07 09:54

So heres the basic outline

function x(){
   // some code 
   function y(){
   //some more code
  }
}

function z(){
  // how do i call function y?
}
<         


        
相关标签:
3条回答
  • 2021-01-07 10:29
    function x(){
       // some code 
      this.y=function(){
       //some more code
      }
    }
    
    function z(){
     var fun_x=new x();
    fun_x.y();
    }
    

    the global namespace is still as it was before this code

    0 讨论(0)
  • 2021-01-07 10:42

    Lots of code, not much explanation.

    function x(){
       // some code 
       function y(){
       //some more code
      }
    }
    

    The above declares y inside x, so it is created as a property of x's variable object each time x is called. y can only be accessed from inside x unless code inside x makes it available from elsewhere.

    function z(){
      // how do i call function y?
    }
    

    To call y from inside z, it must be available on z's scope chain. That can be done by passing it in the function call (making it a property of z's variable object) or making it a property of some object on z's scope chain.

    If the function is to be available to both functions, it makes sense to declare it where it can be accessed by both x and z, or initialize z in such a manner that y is available. e.g.

    var z;
    var x = (function() {
      function y(){}
    
      z = function() {
            // something that calls y;
          };
    
      return function() {
        // x function body
      }
    }());
    

    In the above, x and z both have access to the same y function and it is not created each time x is called. Note that z will be undefined until the code assigning to x is executed.

    Note also that y is only available to x and z, it can't be accessed by any other function (so y might be called a private function and x and z might be called privileged functions).

    0 讨论(0)
  • 2021-01-07 10:49

    1:

    var ref;
    function x(){
       // some code 
       function y(){
       //some more code
      }
      ref = y;
    }
    x();
    
    function z(){
      ref();
    }
    

    2:

    function x() {
    };
    
    x.y = function() { alert('2');};
    
    function z() {  x.y(); }
    

    3:

    function y(){ alert('god'); };
    function x() {
        function a() {
            y();
        }
    }
    function z() {
          y();
    }
    z();
    
    0 讨论(0)
提交回复
热议问题