Is there a clean way to somehow use underscore.js _.extend function (or any other) to create custom Error classes that inherit from base Error class? I’m looking for a backbone-like way to do this.
Tried this :
InternalError = function(message, args) {
message || (message = {});
this.initialize(message, args);
};
_.extend(InternalError.prototype, Error.prototype, {
initialize: function(message, args) {
this.message = message;
this.name = 'InternalError';
}
});
var error1 = new Error('foo');
var error2 = new InternalError('bar');
console.warn(error1, error2);
throw error2;
But it is not working :(.
(Excuse my small parenthesis about prototypal inheritance. You can skip this and see the answer below.
In order for an object to extend another one, the
child‘s prototype must be an instance of it’sparent. You can find many good resources on the web about this, but, unfortunately, many bad ones as well, so I recommend you take a peak at this article : http://javascript.crockford.com/prototypal.html .A new object instantiated via the
newkeyword :new f()returns a copy of it’s prototype object :f.prototype. Acknowledging this, you realize that in order to extend an objectx, your current object’s prototype must be a new x instance :)
you don’t actually need underscore.js for that :
if you really want to use underscore.js :