Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript call nested function

I have the following piece of code:

function initValidation() {     // irrelevant code here     function validate(_block){         // code here     } } 

Is there any way I can call the validate() function outside the initValidation() function? I've tried calling validate() but I think it's only visible inside the parent function.

like image 858
Eduard Luca Avatar asked Jan 11 '12 10:01

Eduard Luca


People also ask

Can you call a nested function in JavaScript?

Generally defining a function inside another function is to scope it to that function and you can't call a nested function in JavaScript. You have to do something inside in outer funciton to make inner funciton available outside it. You will need to return the inner function call.

How do you call a function within a function in JavaScript?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

What is a nested function call?

Nested (or inner, nested) functions are functions that we define inside other functions to directly access the variables and names defined in the enclosing function. Nested functions have many uses, primarily for creating closures and decorators.

Should you nest functions in JavaScript?

no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.


1 Answers

    function initValidation()      {          // irrelevant code here          function validate(_block){              console.log( "test", _block );          }                initValidation.validate = validate;      }        initValidation();      initValidation.validate( "hello" );      //test hello
like image 118
Esailija Avatar answered Sep 25 '22 12:09

Esailija