Reputation: 505
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();
Upvotes: 0
Views: 271
Reputation: 43147
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();
class One_Main {
constructor() {}
static Alpha() {
console.log("Alpha");
}
}
// Make it visible
Alpha = One_Main.Alpha;
function Two_Main() {
Alpha();
}
Two_Main();
function One_Main() {}
One_Main.Alpha = function() {
console.log("Alpha");
}
// Make it visible
Alpha = One_Main.Alpha;
function Two_Main() {
Alpha();
}
Two_Main();
Upvotes: 1
Reputation: 1138
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();
Upvotes: 1
Reputation: 628
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
Upvotes: 1
Reputation: 718
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();
Upvotes: 2