call to a function that inside another function in JavaScript

前端 未结 4 1202
旧巷少年郎
旧巷少年郎 2020-12-12 07:50

I want to call a function that is in another function.

example for the functions:

function funcOne() {
     function funcTw         


        
相关标签:
4条回答
  • 2020-12-12 08:03

    No, You can't call unless you return that function.

    Function2 is private to function1.

    you use

    function funcOne() {
        return {
         funcTwo :function() {    // i want to call to this function
             //do something
         }
       }
    }
    

    EDIT: Structuring code

    function funcOne() {
       var funcTwo = function() {    // private function
            //do something
         }
        return {
          funcTwo : funcTwo      
       }
    }
    

    Now you can call it as:

    funcOne().funcTwo()
    
    0 讨论(0)
  • 2020-12-12 08:11

    As you have it defined in your example, you can't. funcTwo is scoped inside of funcOne, so it can only be called from inside funcOne. You can assign funcTwo to a variable that is scoped outside of funcOne and that would work:

    var funcRef;
    function funcOne() {
        funcRef = function funcTwo() {
    
        }
    }
    

    In this case, funcRef would hold a reference and could be used, but that reference is only set once funcOne has been executed.

    0 讨论(0)
  • 2020-12-12 08:11

    It is not possible as the second function will be created just when the first function is called. it is not existent prior to that.

    You would have to define it outside the first function like so:

    function funcOne() {
    
    }
    function funcTwo() {    // i want to call to this function
        //do something
    }
    

    Or you could also call the first function and return the second function like this:

    function funcOne() {
         function funcTwo() {    // i want to call to this function
             //do something
         }
         return functTwo;
    }
    

    And then call it like this:

    var f = funcOne();
    f();
    
    0 讨论(0)
  • 2020-12-12 08:18

    Reading some Douglas Crockford may help you understand...

    Try recoding as:

    function funcOne() {
       this.funcTwo = function() {
       }
    }
    

    I think you'd have to declare an instance of a funcOne object and then call the funcTwo method of that object. I'm a bit busy at the moment so I can't refine this answer at the moment.

    0 讨论(0)
提交回复
热议问题