js - 模塊化開發的兼容exports的套路


補充:除了第一種的套路,還可以這樣使用第二種。都是用來自執行函數的。第二種的好處是,還可以返回一個true。

// 常用
;(function () {})(); 

// 小技巧(如果不加上!會報錯,加上之后還能返回true呢。)
// 但由於衡返回true。所以只有某些函數是只執行,不在於返回結果的可以用這種。
;!function(){};

 

兼容套路1:適用於遵循CommonJs 、 AMD/CMD 的套路

;(function (root, factory) {
  if (typeof exports === "object") {
    module.exports = factory();
  } else if (typeof define === "function" && define.amd) {
    define([], factory);
  } else {
    root.ol = factory();
  }
}(this,function () {
  // ... 這里編寫你的代碼
  return {

};

})

兼容套路2:jquery的套路

(function( global, factory ) {

    "use strict";

    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 have a `window` with a `document`
        // (such as Node.js), expose a 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 ) {

    //... 這里編寫你的代碼,例如:
    if ( !noGlobal ) {
        window.jQuery = window.$ = jQuery;
    }

    return jQuery;
})

 兼容套路3:第三方中學習過來的簡單套路

"use strict";
(function(exports, undefined) {
    var ns = exports.Best = exports.Best || {};
    
    /***************************/
    /********** Game **********/
    /***************************/
    var Game = ns.Game = function(options) {
        for (var p in options) {
            this[p] = options[p]
        }
    };
    Game.prototype = {};

    /***************************/
    /********** Scene **********/
    /***************************/
    var Scene = ns.Scene = function(options) {
        for (var p in options) {
            this[p] = options[p]
        }
    };
    Scene.prototype = {};
})(this);

// index.js
var game = new Best.Game({
  // some options...
});

是不是很奇怪一個閉包是怎么把變量Best暴漏到外部的?這是因為閉包傳入的this。實際上是window。

另一個重要的知識點:對象的賦值,是值引用的。什么意思呢?舉個例子

window.a = {};
var aa = a;
aa.fuck = 'you';
console.log(a); // => {fuck: "you"}

 我一直以為,在js中只有閉包有值引用。原來TM天天使用的對象的賦值也是值引用的,所以才需要克隆/深淺拷貝的概念

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM