简体   繁体   中英

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(); 

Alpha() is in the scope of One_Main, you can't see it from the global scope. To call Alpha() from outside of One_Main you need to declare it outside of that function.

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

function One_Main(){
    Alpha();
}
One_Main(); 



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

You might want to read about scoping in javascript to understand the problem. https://scotch.io/tutorials/understanding-scope-in-javascript

The function Alpha is not visible inside the Two_Main function

PS: Debugging is useful to learn more about the error. In Chrome you can right click and select Inspect element and look at the console to debug javascript.

Checkout https://raygun.com/blog/debug-javascript/ for more information

I dont know what tutorial are you studying, maybe you are reading about currying method, if that is the case, you can make:

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

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM