CommonJS是服務器端模塊的規範,Node.js採用了這個規範。node
根據CommonJS規範,一個單獨的文件就是一個模塊。每個模塊都是一個單獨的做用域,也就是說,在該模塊內部定義的變量,沒法被其餘模塊讀取,除非定義爲global對象的屬性。jquery
若是jquery要在node中使用,要解決兩個問題:服務器
1.以module.exports的方式導入(CommonJS模塊引入)函數
2.由於是服務器環境,是沒有window變量的。ui
/*! * jQuery JavaScript Library v2.1.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-05-01T17:11Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) {if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { //factory code.... }))
根據代碼,jquery採用一個當即調用函數,判斷是不是CommonJS規範(typeof module === "object" && typeof module.exports === "object"),不是則調用庫函數,是則再判斷有沒有document(走到這步是判斷過沒有window,開啓沒有window模式),有則調用庫函數,this
無則返回一個等待傳入window的匿名函數。spa