顾轶灵
math.js
function add(x, y) {
return x + y;
}
main.js
var a = add(1, 2);
alert(a);
index.html
<script src="math.js"></script>
<script src="main.js"></script>
math.js
var math = {};
math.add = function(x, y) {
return x + y;
}
main.js
var a = math.add(1, 2);
alert(a);
记忆/输入代价 vs. 冲突概率
math.js
(function() {
var math = {};
math.add = function(x, y) {
return x + y;
};
this.math = math;
})();
main.js
(function() {
var a = math.add(1, 2);
alert(a);
})();
eval
document.write()
head.appendChild(script)
模块加载顺序?
goog.provide('mod');
)或不声明(eg. 与文件路径对应)goog.require('mod');
模块不执行,如何获取依赖决定执行顺序?
deps.js
for Closure将依赖声明和模块执行分开(利用 function wrapping)
define(['math'], function(math) {
var a = math.add(1, 2);
alert(a);
});
require
exports
module
math.js
exports.add = function(x, y) {
return x + y;
}
main.js
var add = require('math').add;
var a = add(1, 2);
eval
)的缺陷define(id?, dependencies?, factory);
baidu/dom
./lang
css!./normalize.css
["require", "exports", "module"]
传入 AMD define factory 的 require
函数
define(['require'], function(require) {
//the require in here is a local require.
});
define(function(require, exports, module) {
//the require in here is a local require.
});
用来启动模块加载的全局函数
require(['foo', 'bar'], function (foo, bar) {
foo.doSomething();
});
require(String)
同步返回指定模块接口
define(function(require) {
var a = require('a');
});
Function.prototype.toString()
require(Array, Function)
异步读取多个依赖模块后执行回调
define(function(require) {
require(['a', 'b'], function(a, b) {
//modules a and b are now available for use.
});
});
math.js
define(function() {
var math = {};
math.add = function(x, y) {
return x + y;
};
return math;
});
main.js
require(['math'], function(math) {
var a = math.add(1, 2);
alert(a);
});
math.js
define(function(require, exports) {
exports.add = function(x, y) {
return x + y;
}
});
main.js
define(function(require) {
var add = require('math').add;
var a = add(1, 2);
});
var mod = require(someCondition ? 'a' : 'b');
if (someCondition) {
var a = require('a');
} else {
var a = require('b');
}
eval
define(factory);
define(id?, deps?, factory);
id
与 deps
,在构建时用工具生成define('I am a template. My name is {{name}}.');
define(function(require, exports, module) {
module.exports = new SomeClass();
});
require(String)
同步加载require.async(id, callback?)
异步加载require(Array, Function)
seajs.use()
- EOF -