Oli*_*ier 2 javascript error-handling inheritance underscore.js
是否有一种干净的方式以某种方式使用underscore.js _.extend函数(或任何其他)来创建从基类Error类继承的自定义错误类?我正在寻找一种类似骨干的方式来做到这一点.
试过这个:
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;
Run Code Online (Sandbox Code Playgroud)
但它不起作用:(.
(请原谅我关于原型继承的小括号.你可以跳过这个,看看下面的答案.
为了使一个对象扩展另一个,该child原型必须是它的一个实例parent.你可以在网上找到很多关于这方面的好资源,但不幸的是,还有许多不好的资源,所以我建议你在这篇文章中占据一席之地:http://javascript.crockford.com/prototypal.html.通过关键字实例化
的新对象new:new f()返回它的原型对象的副本:f.prototype.承认这一点,你意识到为了扩展一个对象x,你当前对象的原型必须是一个新的x实例:
function Person(){};
Person.prototype.speak = function(){
alert("I'm a person");
}
function StackoverflowUser(){};
StackoverflowUser.prototype = new Person();
// now StackOverflowUser is a Person too
Run Code Online (Sandbox Code Playgroud)
)
你实际上并不需要underscore.js:
var InternalError = function(msg,args){
return this.initialize(msg||{},args);
}
// inherit from the Error object
InternalError.prototype = new Error();
// overwrite the constructor prop too
InternalError.constructor = InternalError;
InternalError.prototype.initialize = function(msg,args){
this.message = msg;
this.name = 'InternalError';
}
var err = new InternalError("I'm an internal error!");
alert(err instanceof Error); // true
throw err;
Run Code Online (Sandbox Code Playgroud)
如果你真的想使用underscore.js:
var InternalError = function(msg,args){
return this.initialize(msg||{},args);
}
_.extend(InternalError.prototype,new Error(),{
initialize : function(msg,args){
this.message = msg;
this.name = 'InternalError';
},
constructor : InternalError
});
Run Code Online (Sandbox Code Playgroud)