Search code examples
javascriptprototypeunderscore.jsextend

javascript prototype method assign VS underscore _.extend


Is there any difference between following codes?

plain javascript:

Array.prototype.addOrRemove = function(value) {
    var index = _.indexOf(this, value);

    if (index === -1) {
        this.push(value);
    } else {
        this.splice(index, 1);
    }
    return this;
};

underscore extend:

_.extend(Array.prototype, {
    addOrRemove: function(value) {
        var index = _.indexOf(this, value);

        if (index === -1) {
            this.push(value);
        } else {
            this.splice(index, 1);
        }
        return this;
    }
});

Are there any benefits of one over the other one?


Solution

  • In this case, none whatsoever. The underscore method would work better if you are adding multiple new properties/methods.

    However I would advise against modifying the Array prototype unless you know what libraries you are using and what they are doing, it would be very easy to break functionality of certain other libraries (PrototypeJS) and the browser itself if you override certain methods. This is just a side note though...