1

I have a function to clear the user text,but the clearText function is inside the function and variable.

I find some information on Internet,but some solutions are only solve the function in variable and have not two function.

Can anyone tell me how I would call the function in function and variable,please?

And I am sorry about grammar ,English is not my mother language.I am hard to translate using google translate.

Calling a JavaScript function named in a variable I try it but got undefined.

<script>
    var testing = (function(){
        function clearText(){
            /* call other function in this testing function */
        }
        /* other function */
    })();
    function resetInput() {
        /* I call clearText() function here */
    }
</script>
BleeBala
  • 11
  • 3

2 Answers2

6

Unless your first function returns clearText (or makes it accessible outside of that function in some other way), you cannot use it in resetInput.

If it does return clearText, then you can use it via testing:

var testing = (function(){
    function clearText(){
        console.log('clearText() triggered');
        /* some code*/
    }
    /* some function */

    return clearText;    // ****
})();

function resetInput() {
    testing();           // ****
}

resetInput();

If it makes clearText available in some other way (a global variable, etc.), how you'd use it would depend on what that other way is.

Daan
  • 2,680
  • 20
  • 39
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

What you are using is IIFE (immediately Invoked Function Expression). What you do in the following code is inserting the return of nothing into the variable testing.

Execute the following :

var testing = (function() {
  function clearText() {
    console.log('clearText execution');
  }
})();

console.log(testing);

Now what if we return something :

var testing = (function() {
  function clearText() {
    console.log('clearText execution');
  }

  return 'try';
})();

console.log(testing);

If you want to execute the function clearText outside of the IIFE, you have to return a pointer to it, like :

var testing = (function() {
  function clearText() {
    console.log('clearText execution');
    
    return 'done';
  }
  
  return clearText;
})();

console.log(testing);

console.log(testing());

Now, there is no need for IIFE, you could just store the function inside of object and use the reference :

var testing = {
  clearText: () => {
    console.log('clearText execution');

    return 'done';
  }
};

function resetInput() {
  testing.clearText()
}

resetInput();
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69