理解_.js中下划线的声明?

时间:2013-07-15 18:12:26

标签: javascript underscore.js

这是annotated source of _.js的开头。尽管我可以尝试,但我的JavaScript能力还不够高,无法理解这里发生了什么。我希望有人可以给出一个真正的逐步解释。我真的完全不知道除了以某种方式设置_使用之外,下面的代码做了什么,尽管我理解每个单独的表达。

 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._ = _;
  }

2 个答案:

答案 0 :(得分:9)

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._ = _;
}

答案 1 :(得分:3)

嗯,较低的片段是完全不相关的。基本上它将_从闭包导出到全局范围,或者使用module definition system(如果可用)。如果你不使用模块,没什么大不了的。

_函数不应该那么难理解。你需要知道

它的作用是什么:

  1. 如果参数是Underscore实例,则保持不变。
  2. 如果函数未被调用为构造函数(当this上下文不是Underscore实例时),则执行此操作并返回
  3. 将参数包装在当前实例中
相关问题