在我最初开始写 JavaScript 函数时,通常是这样的:
function fun1() { // some code here}function fun2() { // some other code here}...
函数全写在全局环境中,项目很小时,通常不会有什么冲突问题。
但代码多了后,渐渐就发现,函数名称(英文词汇)有点不够用了。于是引入命名空间的概念,开始模块化代码。
命名空间下的函数
在命名空间下,我的代码这样写:
var com = com || {};com.zfanw = com.zfanw || {};com.zfanw.module1 = (function() { // some code here return { func1: func1, ... };}());com.zfanw.module2 = (function() { // some other code here return { func1: func1, ... };}());...
本着要面向对象的原则,执行函数通常我要这么写的:
com.zfanw.module1.func1.apply({},['arg1',arg2]);...
当然,为了少打些字符,我还会在闭包中导入1公共 API 接口:www.Vevb.com
(function($, mod1) { // some code here mod1.func1.apply({},['arg1',arg2]);}(jQuery, com.zfanw.module1));...
至此,代码冲突的可能性已经很小,但代码依赖的问题,多脚本文件管理、阻塞的问题,渐渐浮出水面 – 命名空间的办法开始捉急。
于是 Require.js2 出场。
Require.js
首先了解下 require.js 里模块的概念3:
A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the global namespace. It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to global objects, but instead receive the dependencies as arguments to the function that defines the module.
简单地说,有两点,一、模块作用域自成一体,不污染全局空间;二、模块指明依赖关系,并且依赖是通过参数传递的形式导入的,无需通过全局对象引用 – 依赖同样不污染全局空间。
定义模块
与上面的老长的命名空间方式不同,require.js 用全局方法 define 来定义模块,形式如下:
define(id?, dependencies?, factory); // ? 表示可选项
我且把模块分两种。
无依赖的模块
假如一个模块并不依赖其他模块,那么定义起来是很简单的,比如模块 hello 放在 hello.js 文件中:
define(function() { // some code here return { // some public api };});
有依赖的模块
有依赖的模块要稍稍复杂点,define 时,我们需要罗列出模块的依赖情况:
define(['jquery'], function($) { // 比如这个模块,代码的执行依赖 jQuery,require.js 会先加载 jquery 模块代码,并加以执行,然后将依赖模块 以 $ 的参数形式传入回调函数中,回调函数将执行结果注册为模块 // maybe some code here return { // some public api };});
新闻热点
疑难解答
图片精选