Yang
Yang

Reputation: 6892

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.

Upvotes: 0

Views: 66

Answers (2)

Dai
Dai

Reputation: 155065

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.

Upvotes: 3

JCOC611
JCOC611

Reputation: 19709

You need to execute it:

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

Or:

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

Upvotes: 3

Related Questions