Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is this underscore.js "safe reference" code doing?

I'm learning Backbone, which uses Underscore.

In some examples, I see initialization code to create an empty array of children like this:

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

The Underscore function _ above being called is defined near top of 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;
};

Stepping through in the debugger shows me the return new _(obj) is called at first, so the function is called again and finally this._wrapped = obj is executed. this appears to be referring to _.

I am bewildered. Why not just say this.children = [] in the first place?

like image 712
Thomas Blom Avatar asked Mar 23 '23 10:03

Thomas Blom


1 Answers

Because this.children needs to be a instance of underscore: a specialized class that wraps an array, not just a regular javascript array literal. The code in the _ function just makes sure it's always one _ instance wrapping one regular array, even if you try to rewrap an underscore instance repeatedly, call _ with or without the new keyword.

//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);
like image 139
Peter Lyons Avatar answered Mar 31 '23 18:03

Peter Lyons