1

I have created nested function in one script file A.js, like below:

function A(){
   function B(){}
}

If I want to call function B() in another script file C.js, what should I do?

7
  • 1
    Is there any reason for the nested function? Is there anything else in function A, or is it just function B? Commented Aug 22, 2015 at 13:56
  • 1
    How you would do that depends on many other things. There is no one right answer. Commented Aug 22, 2015 at 13:57
  • You can't, you cannot access another function's scope, unless you expose it. Commented Aug 22, 2015 at 13:58
  • This is like a function closure. You need to somehow return B from A(). Longer answer coming up! Commented Aug 22, 2015 at 14:00
  • This may help: smashingmagazine.com/2009/08/… Commented Aug 22, 2015 at 14:31

3 Answers 3

1

What you want to do seems to be to create a function closure of B using the variables within A(). You can then access this closure B if you return B after you call A(). Then, in C.js, you can access B by calling A and using the return value:

A.js:

function A([parameters]) {
    [variables]
    function B() { [function body] }
    //Return B from A:
    return B;
}

C.js:

//Get B:
var bFunction = A([parameters]):
//Call bFunction:
bFunction();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, exactly what I need~
0

You have to return the nested function:

function A(){
   return function B(){}
}

Then In C.js

var funB = A();
funB();

or

A()();

Comments

0

You have to return the nested function B() from the parent function A().

Your code

function A(){
   function B(){}
}

Updated Code with return statement

function A(){
    return function B(){ //return added

 }     
 }

You can access the child function by adding an additional () Parentheses to the function call like the below example.

A()();

Comments

Your Answer

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.