简体   繁体   中英

javascript how to define an inner function

I want to define an inner function within a function.

function outfunction(){
  function innerfunction(){
      alert('inner'); 
  }
  alert('out');
}

but the innerfunction is never called.

You need to execute it:

function outfunction(){
  function innerfunction(){
      alert('inner'); 
  }
  innerfunction();
  alert('out');
}

Or:

function outfunction(){
  (function(){
      alert('inner'); 
  })();
  alert('out');
}

You need to call the nested function:

function outfunction(){
    function innerfunction(){
        alert('inner'); 
    }
    alert('out');
    innerfunction(); // like this
}

The fact a function is nested only means it has a limited scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM