我如何将我的JavaScript代码分割成单独的文件? [英] How can I split my javascript code into separate files?

查看:149
本文介绍了我如何将我的JavaScript代码分割成单独的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Mozilla的


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 futher search , I understand that the same can be accomplished in JS with namespacing and module pattern - I messed around with it but got very confused ( especially with calling a constructor declared in File1.js into File2.js )

so here is the hierarchy:

But i just can't figure out how to properly make it works

how do i simply go from

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

function Manager () {
  this.reports = [];
}
Manager.prototype = new Employee;

function WorkerBee () {
  this.projects = [];
}
WorkerBee.prototype = new Employee;

function SalesPerson () {
  this.dept = "sales";
  this.quota = 100;
}
SalesPerson.prototype = new WorkerBee;

to this :

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

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

 // WorkerBee.js     
function WorkerBee () {
  this.projects = [];
}
WorkerBee.prototype = new Employee;

 // SalesPerson.js      
function SalesPerson () {
 this.dept = "sales";
 this.quota = 100; 
 }
SalesPerson.prototype = new WorkerBee;

解决方案

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/

这篇关于我如何将我的JavaScript代码分割成单独的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆