How do you call a local function?

2019-02-20 07:28发布

问题:

So heres the basic outline

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

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

I tried

function z(){
   window[x][y];
} 

and

function z(){
x();y();
}

neither works!

回答1:

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).



回答2:

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


回答3:

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