2013-07-15 112 views
3

这是从annotated source of _.js开始。尽管我可以尝试,但我的JavaScript能力还不够高,无法理解这里发生了什么。我希望有人能给出一个真实的一步一步的解释。我真的从字面上不知道以下代码除了以某种方式设置_以供使用,尽管我理解每个单独的表达式。了解_.js中下划线的声明?

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

我的问题,为什么它重要的是什么? – Shawn31313

+4

....试图学习和理解高级编码技术? – Aerovistae

+0

好吧,够公平的。首先,你需要知道'instanceof'的作用。 'instanceof'运算符测试对象是否在其原型链中具有构造函数的原型属性。关于它的更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof – Shawn31313

回答

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

Afaik'根'是全球范围。 – Bergi

+0

@Bergi谢谢,不熟悉下划线的来源。 – matt3141

3

好了,下段是相当无关。基本上它是从关闭出口_到全球范围,或者使用module definition system(如果有的话)。没有什么大不了的,如果你不使用模块,没有什么可以关心的。

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

所以它做什么:

  1. 如果参数是一个下划线情况下,原样返回。
  2. 如果函数不称为构造函数(当this上下文不是一个下划线实例),那么这样做并返回
  3. 否则包裹的说法在目前的情况下
+0

有时我希望SO有合并答案的选项。 – Aerovistae

+0

有维基答案......但为什么,这样你可以upvote他们两个呢? :-) – Bergi