Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call nested function in javascript?

Tags:

javascript

I have two function like this..

function a() {
  function b() {
    alert('reached');
  }
}

how i call function b() from outside of function a()..

like image 271
Rishi Meena Avatar asked Jul 16 '26 08:07

Rishi Meena


1 Answers

In general, you can't. The point of defining a function inside another function is to scope it to that function.

The only way for b to be accessible outside of a is if (when you call a) you do something inside a to make it available outside of a.

This is usually done to create a closure, so that b could access variables from a while not making those variables public. The normal way to do this is to return b.

function a() {
  var c = 0;
  function b() {
    alert(c++);
  }
  return b;
}
var d = a();
d();
d();
d();
var e = a();
e();
e();
e();
like image 124
Quentin Avatar answered Jul 17 '26 21:07

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!