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?
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...
The underscore method would screw your day if you unintendedly override an Array method.
var extention = {
indexOf: function () {
// ...
},
addOrRemove: function(value) {
var index = _.indexOf(this, value);
if (index === -1) {
this.push(value);
} else {
this.splice(index, 1);
}
return this;
}
}
_.extend(Array.prototype, extention);
It could be harder to find the problem if you forgot what you added or which native method you overrided.
By the way the Array.prototype method is more performance friendly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With