Is there any way I can call the validate() function outside the initValidation() function in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

We wish to call the function validate() outside of initValidation(), without necessarily having to call initValidation()

Following is our problem code −

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

In JavaScript, as we know that functions are nothing but objects, so to achieve this we can tweak our code like this −

function initValidation(){
   // irrelevant code here
   function validate(_block){
      // code here
      console.log(_block);
   }
   this.validate = validate;
}

What this tweak does is that it makes our parent function to represent a class now, of which validate is a property and we can access it like this −

const v = new initValidation();
v.validate('Hello world');

Following is the complete code with output −

Example

function initValidation(){
   // irrelevant code here
   function validate(_block){
      // code here
      console.log(_block);
   }
   this.validate = validate;
}
const v = new initValidation();
v.validate('Hello world');

Output

The output in the console will be −

Hello world
raja
Published on 18-Aug-2020 07:01:59
Advertisements