简体   繁体   中英

What is the underscore function for?

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?

You wrap objects with it:

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

And then use Underscore functions on the wrapped object:

_([1, 2, 3, 4]).shuffle()

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(…);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM