JavaScript - How to call a function inside a function?

I have the following JavaScript code:

function parentFunc() {

    function childFunc() {
        ...
    }

    ...
}

// outside of myParentFunc, how do I call myChildFunc() ?
childFunc(); // doesn't work

How do I call childFunc()from outside parentFunc()?

UPDATE

I know that the explicit answer would be to move childFunoutside parentFun, but this is a third-party library that I cannot change.

+5
source share
8 answers

See mapping internal functions to the outside world.

+3
source

This will be one way to do this.

var myChildFunction;

function myParentFunc() {
  //....
  myChildFunction = function () {
    //....
  }
  myChildFunction();
}

myChildFunction();

Here is another way

var myChildFunction = function () {
  //....    
}


function myParentFunc() {
  //....
  myChildFunction();
}

myChildFunction();
+2
source

Yahoo:

myModule = function () {

    //"private" variables:
    var myPrivateVar = "I can be accessed only from within myModule."

    //"private" methods:
    var myPrivateMethod = function () {
        console.log("I can be accessed only from within myModule");
    }

    return {
        myPublicProperty: "I'm accessible as myModule.myPublicProperty."

        myPublicMethod: function () {
            console.log("I'm accessible as myModule.myPublicMethod.");

            //Within myModule, I can access "private" vars and methods:
            console.log(myPrivateVar);
            console.log(myPrivateMethod());
        }
    };
}();

, myPrivateVar myPrivateMethod, , myPublicProperty myPublicMethod .

:

myModule.myPublicMethod();    // Works
myModule.myPublicProperty;    // Works
myModule.myPrivateMethod();   // Doesn't work - private
myModule.myPrivateVar;        // Doesn't work - private
+2

, . , ,

function childFunc() {

,

window.cf = childFunc() {

cf. ( , , .)

+2

, . , OCCATIONALLY , . , , , .

, .

function parentFunction() {
    ...
    childFunction = function() {
    ...
    }
}

childFunction();

childFunction , , , . - .

ABV = {};
ABV.childFunction = function() {
    ...
}
ABV.parentFunction = function() {
    ...
    ABV.childFunction();
    ...
}
ABV.childFunction();

, DWR .. 1 .

, JavaScript, . , . , , , - "", . , .

+1

o_O

, , .js, , , .

0

:

:

function parentFunc() {

   window.childFunc = function(){

   }

}

, :)

, OO-, patter :

function parentFunc() {

   var someVar;

   var childFunc = function(){

   };


   return {
      childFunc,
      someVar
   }

}

parentFunc.childFunc();

.

, , , JS, .

0
function parentFunc() {

    var childFunc = function() {
        ...
    }

    ...
}

childFunc(); // works
-1

All Articles