What makes this underscore.js code a "safe link"?

I am learning Backbone that uses Underscore.

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

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

The subtree _ function called above is defined at the 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; }; 

Passing through the debugger shows that return new _(obj) is called first, so the function is called again and finally this._wrapped = obj is this._wrapped = obj . this seems to refer to _ .

I'm confused. Why not just say this.children = [] in the first place?

+4
source share
2 answers

Since this.children should be an 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 that there is always one _ instance wrapping one regular array, even if you try to recreate the underscore instance again, 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 already a proper _ instance var _doubleWrapped = _(_withoutNew); 
+6
source

From http://underscorejs.org/#chaining

You can use Underscore in an object-oriented or functional style, depending on your preference. The following two lines of code are identical ways of doubling the list of numbers.

 _.map([1, 2, 3], function(n){ return n * 2; }); // Functional style _([1, 2, 3]).map(function(n){ return n * 2; }); // OO style 

Therefore, when the OO style is used, _ is used as a constructor function. Without the first two lines in the constructor function, which "Creates a safe reference to the Underscore object", you will need to use the new keyword, as shown below.

 new _([1, 2, 3]).map(function(n){ return n * 2; }); 

Now you are not :)

+1
source

Source: https://habr.com/ru/post/1502103/


All Articles