0

I'm reading underscore.js sources, trying to understand all of it. The thing I don't yet understand is the definition of _ object. It's source is:

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

In the actual scope (an iife), this refers to the global object and _ has not yet been declared yet.

If you type _ and hit enter in a console (e.g. chrome), assuming you've loaded underscore lib, you'll get the same function definition as above. Well - what is it for? Why isn't it just a normal object {} with all functions/attributes attached as properties?

ducin
  • 25,621
  • 41
  • 157
  • 256

1 Answers1

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 () {...});
user229044
  • 232,980
  • 40
  • 330
  • 338