3

I've been using underscore as a collection of statics.

What is the underscore function for:

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

What is an example of how you would use this?

2 Answers2

4

You wrap objects with it:

_([1, 2, 3, 4]);

And then use Underscore functions on the wrapped object:

_([1, 2, 3, 4]).shuffle()
Blender
  • 289,723
  • 53
  • 439
  • 496
  • It's just a variable name - they could have called it `a`, but `_` obviously works with the script already being called *underscore* – Adam Hopkinson May 04 '13 at 20:29
  • The _ function doesn't actually allow chaining underscore functions - the example above only works because 'map' and 'filter' are built-in array functions. They won't use underscore's implementation, so you could run into compatibility issues with e.g. IE 8. Use the _.chain function for chaining. – Cyanfish May 05 '13 at 03:51
4

You also can use Underscore as a wrapper function, to get a more OOP-like style:

_(val).method(…);
// instead of the equal
_.method(val, …);

These wrapper objects also allow chaining:

_.chain(val).method1(…).method2(…);
// or
_(val).chain().method1(…).method2(…);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375