2

I have two function like this..

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

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

asked Jan 20, 2015 at 10:45
2
  • 3
    You can't. b is only defined inside the scope of a. Commented Jan 20, 2015 at 10:47
  • Some very good answers in this related post here. Commented Oct 7, 2017 at 23:13

3 Answers 3

7

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();
answered Jan 20, 2015 at 10:47

Comments

4

You can rearange your code to this

function a() {
 this.b = function() {
 alert('reached');
 }
}

now instantiate it and run:

c = new a();
c.b();
answered Jan 20, 2015 at 10:52

Comments

0

You will need to return the inner function call.

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

And then you can call this function simply by calling function a like this:

a();

The output will be the required alert.

Benjamin Gruenbaum
277k90 gold badges524 silver badges524 bronze badges
answered Jan 20, 2015 at 10:48

1 Comment

there is no need to return the return-value of b when you just wanna call it

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.