Understanding the declaration of the underscore in _.js?

左心房为你撑大大i 提交于 2019-12-05 21:09:18
var _ = function(obj) {
    // Either serve as the identity function on `_` instances,
    // ... or instantiate a new `_` object for other input.

    // If an `_` instance was passed, return it.
    if (obj instanceof _) return obj;
    // If someone called `_(...)`, rather than `new _(...)`,
    // ... return `new _(...)` to instantiate an instance.
    if (!(this instanceof _)) return new _(obj);

    // If we are instantiating a new `_` object with an underlying,
    // ... object, set that object to the `_wrapped` property.
    this._wrapped = obj;
};

// If there is an exports value (for modularity)...
if (typeof exports !== 'undefined') {
    // If we're in Node.js with module.exports...
    if (typeof module !== 'undefined' && module.exports) {
        // Set the export to `_`
        exports = module.exports = _;
    }
    // Export `_` as `_`
    exports._ = _;
} else {
    // Otherwise, set `_` on the global object, as set at the beginning
    // ... via `(function(){ var root = this; /* ... */ }())`
    root._ = _;
}
Bergi

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 know

So what it does:

  1. If the argument is an Underscore instance, return it unchanged.
  2. If the function is not called as a constructor (when the this context is not an Underscore instance) then do so and return that
  3. Else wrap the argument in the current instance
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!