
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements