Reputation: 31
I have two function like this..
function a() {
function b() {
alert('reached');
}
}
how i call function b() from outside of function a()..
Upvotes: 2
Views: 5953
Reputation: 943510
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();
Upvotes: 7
Reputation: 91
You can rearange your code to this
function a() {
this.b = function() {
alert('reached');
}
}
now instantiate it and run:
c = new a();
c.b();
Upvotes: 4
Reputation: 5329
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.
Upvotes: 0