国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

seaJs使用心得之exports與module.exports的區(qū)別實(shí)例分析

2024-05-06 15:25:41
字體:
供稿:網(wǎng)友

本文實(shí)例講述了seaJs使用心得之exports與module.exports的區(qū)別。分享給大家供大家參考,具體如下:

1. exports 是 module.exports 的 輔助對(duì)象,exports對(duì)外提供api 時(shí)需要用return 返回exports 對(duì)象

2. module.exports 也可直接向外提供api

參考 : https://github.com/seajs/seajs/issues/242

exports Object

exports 是一個(gè)對(duì)象,用來向外提供模塊接口。

define(function(require, exports) { // 對(duì)外提供 foo 屬性 exports.foo = 'bar'; // 對(duì)外提供 doSomething 方法 exports.doSomething = function() {};});

除了給 exports 對(duì)象增加成員,還可以使用 return 直接向外提供接口。

define(function(require) { // 通過 return 直接提供接口 return {  foo: 'bar',  doSomething: function() {} };});

如果 return 語句是模塊中的唯一代碼,還可簡(jiǎn)化為:

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

上面這種格式特別適合定義 JSONP 模塊。

特別注意:下面這種寫法是錯(cuò)誤的!

define(function(require, exports) { // 錯(cuò)誤用法!!! exports = {  foo: 'bar',  doSomething: function() {} };});

正確的寫法是用 return 或者給 module.exports 賦值:

define(function(require, exports, module) { // 正確寫法 module.exports = {  foo: 'bar',  doSomething: function() {} };});

提示:exports 僅僅是 module.exports 的一個(gè)引用。在 factory 內(nèi)部給 exports 重新賦值時(shí),并不會(huì)改變 module.exports 的值。因此給 exports 賦值是無效的,不能用來更改模塊接口。

module.exports Object

當(dāng)前模塊對(duì)外提供的接口。

傳給 factory 構(gòu)造方法的 exports 參數(shù)是 module.exports 對(duì)象的一個(gè)引用。只通過 exports 參數(shù)來提供接口,有時(shí)無法滿足開發(fā)者的所有需求。 比如當(dāng)模塊的接口是某個(gè)類的實(shí)例時(shí),需要通過 module.exports來實(shí)現(xiàn):

define(function(require, exports, module) { // exports 是 module.exports 的一個(gè)引用 console.log(module.exports === exports); // true // 重新給 module.exports 賦值 module.exports = new SomeClass(); // exports 不再等于 module.exports console.log(module.exports === exports); // false});

注意:對(duì) module.exports 的賦值需要同步執(zhí)行,不能放在回調(diào)函數(shù)里。下面這樣是不行的:

// x.jsdefine(function(require, exports, module) { // 錯(cuò)誤用法 setTimeout(function() {  module.exports = { a: "hello" }; }, 0);});

在 y.js 里有調(diào)用到上面的 x.js:

// y.jsdefine(function(require, exports, module) { var x = require('./x'); // 無法立刻得到模塊 x 的屬性 a console.log(x.a); // undefined});

希望本文所述對(duì)大家sea.js程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 天气| 阳山县| 临泽县| 曲麻莱县| 清新县| 蒲城县| 富民县| 龙山县| 神木县| 南汇区| 兴山县| 广元市| 西乌| 宜阳县| 望江县| 牡丹江市| 安国市| 搜索| 耒阳市| 镶黄旗| 西林县| 乌兰浩特市| 湖南省| 金塔县| 三明市| 温宿县| 上饶市| 黄陵县| 麟游县| 饶阳县| 丹阳市| 体育| 金华市| 永城市| 衡阳县| 尚志市| 麦盖提县| 华宁县| 抚顺县| 长泰县| 仙桃市|