How can I split my javascript code into separate files?

前端 未结 3 1765
迷失自我
迷失自我 2021-01-30 18:11

I\'m reading the Javascript Guide from Mozilla And when they contrasted JS to Java , It got me thinking, Java code is easily split up with each class in his own file. after futh

3条回答
  •  清酒与你
    2021-01-30 18:25

    You should have one global namespacing object which every module has to access and write to. Modify your files like so:

    // employe.js
    
    window.myNameSpace = window.myNameSpace || { };
    
    myNameSpace.Employee = function() {
        this.name = "";
        this.dept = "general";
    };
    

    and Manager.js could look like

    // Manager.js
    
    window.myNameSpace = window.myNameSpace || { };
    
    myNameSpace.Manager = function() {
        this.reports = [];
    }
    myNameSpace.Manager.prototype = new myNameSpace.Employee;
    

    This is of course a very simplified example. Because the order of loading files and dependencies is not child-play. There are some good librarys and patterns available, I recommend you looking at requireJS and AMD or CommonJS module patterns. http://requirejs.org/

提交回复
热议问题