4

我正在学习使用下划线的 Backbone。

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

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

_上面调用的 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;
};

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

我很困惑。为什么不一开始就说this.children = []呢?

4

2 回答 2

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);
于 2013-09-13T18:22:14.067 回答
1

来自http://underscorejs.org/#chaining

您可以在面向对象或函数式样式中使用 Underscore,具体取决于您的偏好。以下两行代码是将数字列表加倍的相同方法。

_.map([1, 2, 3], function(n){ return n * 2; }); // Functional style
_([1, 2, 3]).map(function(n){ return n * 2; }); // OO style

所以在使用 OO 风格时,_ 被用作构造函数。如果没有构造函数中“创建对下划线对象的安全引用”的前两行,您将不得不使用new关键字,如下所示

new _([1, 2, 3]).map(function(n){ return n * 2; });

现在你没有:)

于 2014-12-05T13:53:40.003 回答