js

补充:除了第一种的套路,还可以这样使用第二种。都是用来自执行函数的。第二种的好处是,还可以返回一个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天天使用的对象的赋值也是值引用的,所以才需要克隆/深浅拷贝的概念
原文地址:https://www.cnblogs.com/CyLee/p/6422804.html