SeaJS之define函数

seajs.config 用来对 SeaJS 进行配置。jquery

CMD 规范中,一个模块就是一个文件。代码的书写格式以下:define(factory);
define 接受 factory 参数,factory 能够是一个函数,也能够是一个对象或字符串。
factory 为对象、字符串时,表示模块的接口就是该对象、字符串。数组

factory 为函数时,表示是模块的构造方法。
用来定义模块。SeaJS 推崇一个模块一个文件,遵循统一的写法:函数

define(function(require, exports, module) {
// 模块代码
});工具

也能够手动指定模块 id 和依赖,require, exports 和 module 三个参数可酌情省略,具体用法以下。ui

define 也能够接受两个以上参数。字符串 id 表示模块标识,数组 deps 是模块依赖。在开发阶段,推荐不要手写 id 和 deps 参数,由于这两个参数能够在构建阶段经过工具自动生成。对象

define(id, deps, factory)
define(‘hello’, [‘jquery’], function(require, exports, module) {
// 模块代码
});接口

require 是一个方法,接受模块标识做为惟一参数,用来获取其余模块提供的接口。作用域

define(function(require, exports) {开发

// 获取模块 a 的接口
var a = require(‘./a’);字符串

// 调用模块 a 的方法
a.doSomething();

});

在书写模块代码时,必须遵循这些规则。其实只要把 require 看作是语法关键字 就好啦。require 的参数值 必须 是字符串直接量。不要重命名 require 函数,或在任何做用域中给 require 从新赋值。模块 factory 构造方法的第一个参数 必须 命名为 require 。

exports 是一个对象,用来向外提供模块接口。

define(function(require, exports) {

// 对外提供 foo 属性
exports.foo = ‘bar’;

// 对外提供 doSomething 方法
exports.doSomething = function() {};

});

除了给 exports 对象增长成员,还可使用 return 直接向外提供接口。

define(function(require) {

// 经过 return 直接提供接口
return {
foo: ‘bar’,
doSomething: function() {};
};

});

若是 return 语句是模块中的惟一代码,还可简化为:

define({
foo: ‘bar’,
doSomething: function() {};
});

提示:exports 仅仅是 module.exports 的一个引用。在 factory 内部给 exports 从新赋值时,并不会改变 module.exports 的值。所以给 exports 赋值是无效的,不能用来更改模块接口。

module 是一个对象,上面存储了与当前模块相关联的一些属性和方法。

module.id 模块的惟一标识。

define(‘id’, [], function(require, exports, module) {

// 模块代码

});

上面代码中,define 的第一个参数就是模块标识。

module.exports 当前模块对外提供的接口。

传给 factory 构造方法的 exports 参数是 module.exports 对象的一个引用。只经过 exports 参数来提供接口,有时没法知足开发者的全部需求。 好比当模块的接口是某个类的实例时,须要经过 module.exports 来实现:

define(function(require, exports, module) {

// exports 是 module.exports 的一个引用
console.log(module.exports === exports); // true

// 从新给 module.exports 赋值
module.exports = new SomeClass();

// exports 再也不等于 module.exports
console.log(module.exports === exports); // false

});

相关文章
相关标签/搜索