I am calling a function on button click like this:
<input type="button" onclick="outer();" value="ACTION">?
function outer() {
alert("hi");
}
It works fine and I get an alert:
Now when I do like this:
function outer() {
function inner() {
alert("hi");
}
}
Why don't I get an alert?
Though inner function has a scope available in outer function.
This question is related to
javascript
function
scope
you can also just use return:
function outer() {
function inner() {
alert("hi");
}
return inner();
}
outer();
You can also try this.Here you are returning the function "inside" and invoking with the second set of parenthesis.
function outer() {
return (function inside(){
console.log("Inside inside function");
});
}
outer()();
Or
function outer2() {
let inside = function inside(){
console.log("Inside inside");
};
return inside;
}
outer2()();
If you want to call the "inner" function with the "outer" function, you can do this:
function outer() {
function inner() {
alert("hi");
}
return { inner };
}
And on "onclick" event you call the function like this:
<input type="button" onclick="outer().inner();" value="ACTION">?
Again, not a direct answer to the question, but was led here by a web search. Ended up exposing the inner function without using return, etc. by simply assigning it to a global variable.
var fname;
function outer() {
function inner() {
console.log("hi");
}
fname = inner;
}
Now just
fname();
You are not calling the function inner
, just defining it.
function outer() {
function inner() {
alert("hi");
}
inner(); //Call the inner function
}
You could make it into a module and expose your inner function by returning it in an Object.
function outer() {
function inner() {
console.log("hi");
}
return {
inner: inner
};
}
var foo = outer();
foo.inner();
Source: Stackoverflow.com