本文實例講述了seaJs使用心得之exports與module.exports的區別。分享給大家供大家參考,具體如下:
1. exports 是 module.exports 的 輔助對象,exports對外提供api 時需要用return 返回exports 對象
2. module.exports 也可直接向外提供api
參考 : https://github.com/seajs/seajs/issues/242
exports Object
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() {} });
上面這種格式特別適合定義 JSONP 模塊。
特別注意:下面這種寫法是錯誤的!
define(function(require, exports) { // 錯誤用法??!! exports = { foo: 'bar', doSomething: function() {} }; });
正確的寫法是用 return 或者給 module.exports 賦值:
define(function(require, exports, module) { // 正確寫法 module.exports = { foo: 'bar', doSomething: function() {} }; });
提示:exports 僅僅是 module.exports 的一個引用。在 factory 內部給 exports 重新賦值時,并不會改變 module.exports 的值。因此給 exports 賦值是無效的,不能用來更改模塊接口。
module.exports Object
當前模塊對外提供的接口。
傳給 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 的賦值需要同步執行,不能放在回調函數里。下面這樣是不行的:
// x.jsdefine(function(require, exports, module) { // 錯誤用法 setTimeout(function() { module.exports = { a: "hello" }; }, 0); });
在 y.js 里有調用到上面的 x.js:
// y.jsdefine(function(require, exports, module) { var x = require('./x'); // 無法立刻得到模塊 x 的屬性 a console.log(x.a); // undefined });
希望本文所述對大家sea.js程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。