Could everyone tell me how to call a function inside a function? For example :
function betterExampleNeeded() {
var a = 1;
function oneMoreThanA() {
return a + 1;
}
return oneMoreThanA();
}
How to call oneMoreThanA( ) Thanks in advance
asked Mar 23, 2015 at 20:12
Xuzheng Wang
5326 silver badges17 bronze badges
1 Answer 1
You're calling oneMoreThanA in your example.
If you want to call it from outside your betterExampleNeeded function, then you'll need to have betterExampleNeeded make the functino reference available outside of it, by:
- Returning it
- Assigning it to a variable in the containing scope
- Assigning it to an object property on an argument passed into it
...or similar.
For instance:
function betterExampleNeeded() {
var a = 1;
function oneMoreThanA() {
return a + 1;
}
return oneMoreThanA; // <=== Note! No ()
}
var f = betterExampleNeeded();
console.log(f()); // 2
console.log(f()); // 2
console.log(f()); // 2
Or we could even modify a:
function betterExampleNeeded() {
var a = 1;
function oneMoreThanA() {
return ++a; // <=== Modify `a`
}
return oneMoreThanA;
}
var f = betterExampleNeeded();
console.log(f()); // 2
console.log(f()); // 3
console.log(f()); // 4
answered Mar 23, 2015 at 20:21
T.J. Crowder
1.1m201 gold badges2k silver badges2k bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Xuzheng Wang
Thanks for response. I got some problems in understanding javascript. Please correct me , if I am wrong. A function is a object, if I assign this function to variable. For example, var a = function betterExampleNeeded() { var a = 1; function oneMoreThanA() { return a + 1; } return oneMoreThanA(); } can I call the function inside by using a.oneMoreThanA() ? Apologies for my format, I dont know how to adjust here.
Xuzheng Wang
sorry, I should have removed "betterExampleNeeded" to make it a anonymous function
T.J. Crowder
@XuzhengWang: No, because although functions are objects, you haven't set a property on that function with the name
oneMoreThanA. The oneMoreThanA inside that function is completely private to code within the function, unless (again) you do one of the things listed above to expose it to the outside world.T.J. Crowder
@XuzhengWang: Or to put it another way: A function declared inside another function is very much like a local variable. So just like local variables don't become properties of the function instance, functions declared inside them don't either.
Xuzheng Wang
Thanks a lot! I got confused about the difference between var a = function ( ){} and var a = { }.
lang-js
betterExampleNeededoneMoreThanA()in your sample?