首頁  >  文章  >  web前端  >  seaJs中關於exports和module.exports的差異詳解

seaJs中關於exports和module.exports的差異詳解

黄舟
黄舟原創
2017-10-14 10:13:031618瀏覽

這篇文章主要介紹了seaJs使用心得之exports與module.exports的區別,結合實例形式分析了exports與module.exports具體功能、使用方法及相關操作注意事項,需要的朋友可以參考下

本文實例講述了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
});

以上是seaJs中關於exports和module.exports的差異詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn