How can I split my javascript code into separate files?

扶醉桌前 提交于 2019-12-02 16:20:00

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/

You don't need to do anything differently. Just include the script files and they work as if it was a single file.

Javascript doesn't have file scope. Once the code is parsed it doesn't matter where the code came from.

For small and medium projects like a website or game, the native namespacing and constructors work very well. They are a poor choice when the loading order is too complex to handle without some sort of autoloading.

index.html:

<script src="Employee.js"></script>
<script src="Manager.js"></script>

Manager.js:

var Manager = function() {
    var employee1 = new window.Employee(this);
    var employee2 = new window.Employee(this);
};

Employee.js:

var Employee = function(boss) {
    // work stuff here
    this.wage = 5;
};

Note, properties inside the employee constructor function are visible to the manager. The new word signals a constructor. This is also possible without a constructor by returning an object with properties instead of a function as shown above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!