Emil A.
Emil A.

Reputation: 3445

Underscore.js core

I'm going through the code of the underscore library just to see how it's been built:

http://underscorejs.org/underscore.js

I understand most of it, it contains comments, however there are parts which I do not understand yet:

// 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;
};

I've changed it a little just to learn how it works:

function _(obj) {

    if (obj instanceof _) {
        return obj;
    }

    if (!(this instanceof _)) {
        return new _(obj);
    }

    this._wrapped = obj;
}

// just an example, if statement to check if array 
// is really an array should be added

_.sum = function (array) {
    var sum = 0;
    for (var i = 0, ilen = array.length; i < ilen; i += 1) {
        sum += array[i];
    }
    return sum;
}

_.sum([1, 2, 3, 4, 5]); // 15

Ok, so now I'll create a new instance with the _ constructor. The new keyword will be used even if I don't provide it, everything works fine.

var _a = _([1, 2, 3, 4, 5]); // { _wrapped: [1, 2, 3, 4, 5] }

What's the purpose of the following line?

if (obj instanceof _) return obj;

I can remove it and the code still works correctly. Is it used only to handle the following case?

var _b = _(_a);

Upvotes: 1

Views: 114

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

Yes, it is used to handle the 'already wrapped' case.

If you pass an underscore instance to _ it'll return that instance instead of wrapping it. That's the purpose of :

if (obj instanceof _) return obj;

As proof - here is the bug adding this in solved.

Upvotes: 2

Related Questions