This is from the beginning of the annotated source of _.js. Try though I may, my JavaScript abilities are not at a high enough level to understand what's going on here. I'm hoping someone can give a real step by step explanation. I really have literally no idea what the code below does besides somehow setting up the _ for use, despite that I understand each individual expression.
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._ = _;
}
Well, the lower snippet is quite unrelated. Basically it's exporting the
_
from the closure to the global scope, or using a module definition system if available. No great deal, and nothing to care about if you don't use modules.The
_
function shouldn't be that hard to understand. You need to knownew
operator do?instanceof
operator work?So what it does:
this
context is not an Underscore instance) then do so and return that