首頁  >  文章  >  web前端  >  exports與module.exports使用方法

exports與module.exports使用方法

php中世界最好的语言
php中世界最好的语言原創
2018-04-17 15:44:217445瀏覽

這次帶給大家exports與module.exports使用方法,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
});

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

vue中陣列變化偵測問題

#JS上傳檔案時顯示進度條

以上是exports與module.exports使用方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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