1

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);
0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Here is the commit where it was changed github.com/jashkenas/underscore/commit/… it contains a unit test added to enforce this behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.