这个underscore.js"安全参考"代码在做什么?

Tho*_*lom 4 javascript underscore.js

我正在学习使用Underscore的Backbone.

在一些例子中,我看到初始化代码创建一个空的子数组,如下所示:

// inside a constructor function for a view object that will be extended:
this.children = _([]);
Run Code Online (Sandbox Code Playgroud)

调用_上面的Underscore函数是在Underscore.js顶部附近定义的:

// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
};
Run Code Online (Sandbox Code Playgroud)

在调试器中单步执行会显示我return new _(obj)最初被调用,因此再次调用该函数并最终this._wrapped = obj执行. this似乎是指_.

我很困惑.为什么不this.children = []首先说出来?

Pet*_*ons 6

因为this.children需要是下划线的实例:包装数组的专用类,而不仅仅是常规的javascript数组文字._函数中的代码只是确保它总是_包装一个常规数组的一个实例,即使您尝试重复重写下划线实例,使用或不使用new关键字调用_ .

//new _ instance wrapping an array. Straightforward.
var _withNew = new _([]);

//automatically calls `new` for you and returns that, resulting in same as above
var _withoutNew = _([]);

//just gives you _withoutNew back since it's already a proper _ instance
var _doubleWrapped = _(_withoutNew);
Run Code Online (Sandbox Code Playgroud)