使用下划线.js创建javascript自定义错误对象的快捷方式?
是否有一种干净的方法可以使用underline.js u2;.extend函数(或任何其他函数)创建从基本错误类继承的自定义错误类?我正在寻找一种像脊梁骨一样的方法来做这件事 我试过这个:使用下划线.js创建javascript自定义错误对象的快捷方式?,javascript,inheritance,error-handling,underscore.js,Javascript,Inheritance,Error Handling,Underscore.js,是否有一种干净的方法可以使用underline.js u2;.extend函数(或任何其他函数)创建从基本错误类继承的自定义错误类?我正在寻找一种像脊梁骨一样的方法来做这件事 我试过这个: InternalError = function(message, args) { message || (message = {}); this.initialize(message, args); }; _.extend(InternalError.prototype, Error.pro
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;
但它不起作用:(.扩展错误对象(以及通常的主机对象)并不能在所有浏览器中都起作用。
错误。IE上甚至不存在原型。错误
对象也不需要扩展。错误
对象,但只需使用任何自定义对象即可,甚至对象文字:{message Really bad error}
(请原谅我的小括号中关于原型继承的内容。您可以跳过这一部分,然后查看下面的答案
为了让一个对象扩展另一个对象,子对象的原型必须是它的父对象的一个实例。你可以在网上找到很多关于这方面的好资源,但不幸的是,也有很多不好的资源,所以我建议你在本文中登峰造极:。
通过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
)
实际上,您不需要下划线.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;
如果确实要使用下划线.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
});
-1表示“错误。IE上甚至不存在原型”,这是不正确的。此外,Error
不是一个主机对象。即使是这样,IE自IE 8以来已经为大多数主机对象提供了prototype
。扩展Error
对象应该可以在所有实现至少第三版ECMA-262.+1的浏览器中实现,这是一个很好的答案,但我会指定InternalError.protottype.constructor=InternalError
,而不是将constructor
设置为实例属性。thx,我已经更新了示例,将构造函数包含在原型中。@gion_13您似乎仍然在使用InternalError.constructor=InternalError;
而不是InternalError.prototype.constructor=InternalError代码>如建议的那样