下划线 -> var _ 函数
Underscore -> var _ function
谁能准确解释一下这是怎么回事?
它是下划线库的心跳,因为它公开了 _
供使用,但这如何将 _
公开为公开可用的东西?
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
如果我在控制台中键入 _
,将返回以下内容:
_(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
}
然而.....正上方我们有
var root = this;
如果您在控制台中输入 root
它 returns root is not defined
因为它在 IIFE 的范围内受到保护。这似乎是最小特权原则的一个很好的例子。
我几乎可以肯定是 new _(obj)
的使用暴露了 _
,但如果能解释一下此函数,我们将不胜感激。传入 obj
的示例是什么?下划线方法之一?
如果需要更多上下文,来源,尤其是此部分可以是 found here。
在这些行下面,有一些代码:
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
如果您在浏览器环境中,exports
将是 undefined
,因此 root._
将设置为 _
。 root
置顶为this
,this
默认值为window
.
谁能准确解释一下这是怎么回事?
它是下划线库的心跳,因为它公开了 _
供使用,但这如何将 _
公开为公开可用的东西?
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
如果我在控制台中键入 _
,将返回以下内容:
_(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
}
然而.....正上方我们有
var root = this;
如果您在控制台中输入 root
它 returns root is not defined
因为它在 IIFE 的范围内受到保护。这似乎是最小特权原则的一个很好的例子。
我几乎可以肯定是 new _(obj)
的使用暴露了 _
,但如果能解释一下此函数,我们将不胜感激。传入 obj
的示例是什么?下划线方法之一?
如果需要更多上下文,来源,尤其是此部分可以是 found here。
在这些行下面,有一些代码:
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
如果您在浏览器环境中,exports
将是 undefined
,因此 root._
将设置为 _
。 root
置顶为this
,this
默认值为window
.