After confusing the encapsulation of different JS libraries for a while, I finally got a clue. Roughly:
So I found an early version of jQuery. The version number is 1.7.1. The encapsulation code is roughly as follows
of which
So we can create a similar package
}
})(window)
1. Define jQuery symbols and global calls
2.Asynchronous support
So I looked for an earlier jQuery package, and the method was roughly the same, except. .
var $ = jQuery;
};
It’s such a magical judgment method that we can’t rewrite the jQuery in the previous step. So I had to take a look at what the latest jQuery package looks like. So I opened 2.1.1 and found that in addition to adding a lot of functions, the basic idea remains the same
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;
}));
Backbone 封装
打开了Backbone看了一下
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;
}));
除了异步支持,也体现了其对于jQuery和underscore的依赖,百
Underscore 封装
于是,又看了看Underscore,发现这个库又占领了一个符号 _
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));