Introduction to anonymous functions and encapsulation in Javascript

  • 2020-05-16 06:19:56
  • OfStack

After confusing the encapsulation of different JS libraries for a while, I finally got some idea. Roughly:


create 1 Self - calling anonymous functions, design parameters window And the incoming window Object.

And the purpose of this process is to say,

So that their own code will not be contaminated by other code, but also can not pollute other code.

jQuery encapsulation

So I looked for an earlier version of jQuery, version 1.7.1, and the package code looked something like this


(function( window, undefined ) {
var jQuery = (function() {console.log('hello');});
window.jQuery = window.$ = jQuery;
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
    define( "jquery", [], function () { return jQuery; } );
}
})( window );

One of the


console.log('hello');

Is to verify that it works as stated at the beginning, so we can call jQuery in window

window.$

Or is it

window.jQuery

So we can create a similar wrapper


(function(window, undefined) {
    var PH = function() {     }
})(window)

It's only two steps less than that

1. Define the symbols and global calls of jQuery
2. Asynchronous support

So I looked for the packaging of the earlier jQuery, and the method was about 1, except for.


if (typeof window.jQuery == "undefined") {
    var jQuery = function() {};
    if (typeof $ != "undefined")
        jQuery._$ = $;     var $ = jQuery;
};

It's so amazing that we can't rewrite jQuery from step 1. So we have to see what the latest jQuery packaging looks like. So I opened 2.1.1 and found that in addition to adding a lot of functions, the idea was basically the same


(function(global, factory) {     if (typeof module === "object" && typeof module.exports === "object") {
        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);
    } }(typeof window !== "undefined" ? window : this, function(window, noGlobal) {
    var jQuery = function() {
        console.log('jQuery');
    };
    if (typeof define === "function" && define.amd) {
        define("jquery", [], function() {
            return jQuery;
        });
    };
    strundefined = typeof undefined;
    if (typeof noGlobal === strundefined) {
        window.jQuery = window.$ = jQuery;
    };
    return jQuery;
}));

In the case of a browser

typeof module ="undefined"

So the above situation is judged in the case of Node.js and so on, which also indicates that jQuery is becoming bloated.

Backbone encapsulation

Open Backbone and look 1


(function(root, factory) {     if (typeof define === 'function' && define.amd) {
        define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
            root.Backbone = factory(root, exports, _, $);
        });     } else if (typeof exports !== 'undefined') {
        var _ = require('underscore');
        factory(root, exports, _);     } else {
        root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
    } }(this, function(root, Backbone, _, $) {
    Backbone.$ = $;
    return Backbone; }));

In addition to asynchronous support, it also shows its dependence on jQuery and underscore


        define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
            root.Backbone = factory(root, exports, _, $);
        });

Indicates that backbone is native to requirejs.

Underscore encapsulation
So, I looked at Underscore again and found that the library had captured another symbol _


(function() {
    var root = this;
    var _ = function(obj) {
        if (obj instanceof _) return obj;
        if (!(this instanceof _)) return new _(obj);
        this._wrapped = obj;
    };     if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = _;
        }
        exports._ = _;
    } else {
        root._ = _;
    }     if (typeof define === 'function' && define.amd) {
        define('underscore', [], function() {
            return _;
        });
    }
}.call(this));

It's pretty much anonymous in general, except for the call() method at the end.


Related articles: