CMD的几个常用API
2020-12-13 14:50
标签:style http io color os ar 使用 sp strong 全局函数,用来定义模块。 参数: 1.id 模块标识(可省略) 2.deps模块依赖(比如jquery)(可省略) 3.factory:可能是: (1)对象 (2)字符串 ①和②通常表示模块的接口 (3)函数:表示模块的构造方法,执行该构造方法,可以获取该模块向外提供的接口。 factory为函数的情况,在执行时,会默认传入三个参数: require是一个方法,接受 模块标识 作为唯一参数,用来获取其他模块提供的接口,同步往下执行 异步回调执行,用来加载可延迟异步加载的模块,参数有两个:id和callback 给exports对象增加成员, (1)define(function(require) { 当前模块对外提供的接口。 传给 对 CMD的几个常用API 标签:style http io color os ar 使用 sp strong 原文地址:http://www.cnblogs.com/lihongfei0502/p/4066539.html一: define, ①require是一个方法,接受 模块标识 作为唯一参数,用来获取其他模块提供的接口②exports ③module二:require, 三:require.asyncrequire.async 方法用来在模块内部异步加载模块,并在加载完成后执行指定回调。callback 参数可选。四:exports, exports 是一个对象,用来向外提供模块接口,exports 对象增加成员,还可以使用 return 直接向外提供接口
// 通过 return 直接提供接口
return {
foo: ‘bar‘,
doSomething: function() {}
};
(2)define(function(require, exports, module) {
// 正确写法
module.exports = {
foo: ‘bar‘,
doSomething: function() {}
};
});
});五: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
});
module.exports 的赋值需要同步执行,不能放在回调函数里,如下面这种方法就是错误的:define(function(require, exports, module) {
// 错误用法
setTimeout(function() {
module.exports = { a: "hello" };
}, 0);
});