Call Validate Function Outside InitValidation in JavaScript



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
Updated on: 2020-08-18T07:02:11+05:30

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements