Vlad Stoica
Vlad Stoica

Reputation: 75

Accessing main() functions from another javascript file

I have this issue where i have 2 files 1) containing main() and other stuff related to the main UI inside main() there are some functions 2) another file that makes the connection from the server to the UI

I am unable to find any solution to call functions from main() from the secondary file ( I know this is not a godd programming-design but i've already written a lot of code)

Thanks:)

Upvotes: 1

Views: 108

Answers (1)

lbstr
lbstr

Reputation: 2832

In js, functions are your scope constraints. So, consider the following code:

function main(){
    function callMom(){
        alert('hi mom!');
    }
}

function goAboutYourDay(){
    brushTeeth(); // works
    callMom(); // wont work
}

function brushTeeth(){
    alert('brush brush brush');
}

Given your situation, you might consider returning some of main's functions like this:

function main(){
    var callMom = function(){ 
        alert('hi mom!');
    }

    return {
        callMommy: callMom
    };
}

function goAboutYourDay(){
    var m = main();
    m.callMommy(); 
}

Here's how you would do it with prototypes:

var Main = function(){
    this.message = "Will you send some candy?";
};

Main.prototype.callMom = function(){
    alert('Hi Mom! ' + this.message);
};

function otherFile(){
    // you could create a new instance of Main if there isn't one available to you here
    var main = new Main(); 
    main.callMom();    
}

otherFile();
​

Here are a few jsfiddles so that you can play with these examples:
http://jsfiddle.net/lbstr/A3dSB/
http://jsfiddle.net/lbstr/FyDAL/
http://jsfiddle.net/lbstr/2TLu2/

Upvotes: 1

Related Questions