0

我正在阅读underscore.js sources,试图理解所有内容。我还不明白的是_对象的定义。它的来源是:

var _ = function(obj) {
  if (obj instanceof _) return obj;
  if (!(this instanceof _)) return new _(obj);
  this._wrapped = obj;
};

在实际作用域(一个 iife)中,this 指的是全局对象,_尚未声明。

如果您_在控制台(例如 chrome)中键入并按回车键,假设您已经加载了下划线库,您将获得与上面相同的函数定义。好吧 - 它有什么用?为什么它不只是一个{}将所有功能/属性附加为属性的普通对象?

4

1 回答 1

6

Underscore's _ function is is meant to work as a wrapper around other objects, like arrays, it's not just a collection of methods.

It needs to do both this:

_.each(array, function () {...});

and this:

_(array).each(function () {...});
于 2013-08-19T18:19:50.403 回答