George Stoqnov George Stoqnov -4 years ago 36
Javascript Question

How to call a function from outside the main function?

I am currently trying to learn javascript and what I want to achieve is to call a function, from outside the main function. For a better idea, I left the code which I am currently exercising on. I will be extremely grateful If someone can explain to me why exactly this function is not working. Thank you in advance.



function One_Main(){
function Alpha(){
console.log("Alpha");
}
}
One_Main();



function Two_Main(){
Alpha();
}
Two_Main();




Answer Source

It's not working because Alpha is not visible outside of One_Main.

To make it visible, you can define One_Main as an object, then make Alpha a property of One_Main.

To fix your code, do this:

function One_Main() {
  this.Alpha = function() {
    console.log("Alpha");
  }
}

// Make it visible
Alpha = new One_Main().Alpha;

function Two_Main() {
  Alpha();
}
Two_Main();

ES2015 Style

class One_Main {
    constructor() {}
    static Alpha() {
        console.log("Alpha");
    }
}

// Make it visible
Alpha = One_Main.Alpha;

function Two_Main() {
    Alpha();
}

Two_Main();

As a simple property in pure JS

function One_Main() {}

One_Main.Alpha = function() {
  console.log("Alpha");
}

// Make it visible
Alpha = One_Main.Alpha;

function Two_Main() {
  Alpha();
}

Two_Main();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download