简体   繁体   English

javascript如何定义内部函数

[英]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. 函数嵌套的事实仅意味着其范围有限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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