【问题标题】:Understanding the declaration of the underscore in _.js?理解 _.js 中下划线的声明?
【发布时间】:2013-07-13 17:07:58
【问题描述】:

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

【问题讨论】:

标签: javascript underscore.js


【解决方案1】:
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._ = _;
}

【讨论】:

  • Afaik root 是全局范围。
  • @Bergi 谢谢,不熟悉下划线来源。
【解决方案2】:

嗯,较低的 sn-p 是完全无关的。基本上它将_ 从闭包导出到全局范围,或者使用module definition system(如果有)。没什么大不了的,如果你不使用模块也没什么好关心的。

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

那么它的作用:

  1. 如果参数是下划线实例,则原样返回。
  2. 如果函数没有作为构造函数调用(当this 上下文不是下划线实例时),则执行此操作并返回它
  3. 否则将参数包装在当前实例中

【讨论】:

  • 有时我希望 SO 可以选择合并答案。
  • 有 wiki 的答案……但是为什么,这样你就可以对他们两个都投赞成票? :-)
猜你喜欢
  • 2015-03-02
  • 2016-07-21
  • 2010-10-07
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多