在Node.js中對模組載入和執行進行了包裝,使得模組檔案中的變數在一個閉包中,不會污染全域變量,和他人衝突。
前端模組通常是我們開發人員為了避免和他人衝突才把模組程式碼放置在一個閉包中。
如何封裝Node.js和前端通用的模組,我們可以參考Underscore.js 實現,他就是一個Node.js和前端通用的功能函數模組,查看程式碼:
// Creuseate a safe below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _objapp); = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we // backwards-compatibility for the old `require()` API. If we 're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (type ) {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _; exports = module. 鎠{
root._ = _;
}
透過判斷exports是否存在來決定將局部變數_ 賦值給exports,向後相容於舊的require() API,如果在瀏覽器中,透過一個字串識別碼「_」作為一個全域物件;完整的閉包如下:
複製程式碼
/ / Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Create a safe reference to the Underscore object for below below. 🎜> var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(objwr);
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API.
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined' 🎜> if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
} exports = module.exports = _;
} 🎜 > root._ = _;
}
}).call(this);
透過function定義建置了一個閉包,call(this)是將function在this物件下調用,以避免內部變數污染到全域作用域。瀏覽器中,this指向的是全域物件(window物件),將“_”變數賦在全域物件上“root._”,以供外部呼叫。
和Underscore.js 類似的Lo-Dash,也是使用了類似的方案,只是相容了AMD模組載入的相容:
複製程式碼
程式碼如下:
;(function() {
/**Used as a safe reference for `undefined` in pre ES5 environments*/
var undefined;
/**Used to determine if values are of the language type Object*/
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/**Used as a reference to the global object*/
var root = (objectTypes[typeof window] && window) || this;
/**Detect free variable `exports`*/
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
/**Detect free variable `module`*/
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/**Detect the popular CommonJS extension `module.exports`*/
var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
/*--------------------------------------------------------------------------*/
// expose Lo-Dash
var _ = runInContext();
// some AMD build optimizers, like r.js, check for condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lo-Dash to the global object even when an AMD loader is present in
// case Lo-Dash was injected by a third-party script and not intended to be
// loaded as a module. The global assignment can be reverted in the Lo-Dash
// module by its `noConflict()` method.
root._ = _;
// define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module
define(function() {
return _;
});
}
// check for `exports` after `define` in case a build optimizer adds an `exports` object
else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = _)._ = _;
}
// in Narwhal or Rhino -require
else {
freeExports._ = _;
}
}
else {
// in a browser or Rhino
root._ = _;
}
}.call(this));
再来看看Moment.js的封装闭包主要代码:
(function (未定義) {
var moment;
// nodeJS をチェック
var hasModule = (typeof module !== 'unknown' && module.exports);
/*************************************
露出の瞬間
******** ****************************/
function makeGlobal(deprecate) {
var warning = false, local_moment = moment;
/*global ender:false */
if (エンダーの種類!== '未定義') {
return;
}
// ここで、「this」はブラウザの「ウィンドウ」、またはサーバーの「グローバル」を意味します
// 「モーメント」を追加` 文字列識別子を介したグローバル オブジェクトとして、
// Closure Compiler の「上級」モード用
if (非推奨) {
this.moment = function () {
if (!warned && console && console.warn) {
warn = true;
console.warn(
「グローバル スコープを介した Moment へのアクセスは "
「非推奨であり、今後の「
」」で削除される予定ですrelease.");
}
return local_moment.apply(null, argument);
};
} else {
this['moment '] = 瞬間;
}
}
// CommonJS モジュールが定義されています
if (hasModule) {
module.exports = moment;
makeGlobal(true);
} else if (typeof define = == "function" &&define.amd) {
define("moment", function (require,exports, module) {
if (module.config().noGlobal !== true) {
// ユーザーが noGlobal を指定した場合、ユーザーは global を認識します
makeGlobal(module.config().noGlobal === unknown);
}
return moment;
});
} else {
makeGlobal();
}
}).call(this);
上の画面の例は、封入Node.jsとフロントエンドで見られます。汎用的なモジュールの場合は、次の逻辑を使用できます:
if ( typeofexports !== "未定義") {
exports.** = **;
} else {
this.** = **;
}
つまり、エクスポート オブジェクトが存在する場合は、局所的な値がエクスポート オブジェクトにロードされ、存在しない場合は、ローカル オブジェクト全体にロードされます。 🎜>
复制代码

javaandjavascriptaredistinctlanguages:javaisusedforenterpriseandmobileapps,while javascriptifforInteractiveWebpages.1)JavaisComcompoppored,statieldinglationallyTypted,statilly tater astrunsonjvm.2)

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版
中文版,非常好用

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)