2011-11-14 35 views
2

有没有一种干净的方式来以某种方式使用underscore.js _.extend函数(或任何其他)来创建自定义的错误类从基类错误类继承?我正在寻找一个像骨干一样的方式来做到这一点。使用underscore.js创建javascript自定义错误对象的快捷方式?

尝试这样:

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; 

但它不工作:(

回答

8

原谅我的小关于原型遗传的括号。你可以跳过这个并看到下面的答案。

为了让对象扩展另一个对象,child的原型必须是其实例parent。你可以在网上找到很多关于这方面的优秀资源,但不幸的是,也有很多不好的资源,所以我建议你在本文中采取一个高峰:http://javascript.crockford.com/prototypal.html
A 新对象通过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 

你实际上并不需要为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; 

,如果你真的想用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 
}); 
+2

+1,并且答案很好,但我会指定InternalError.prototype.constructor = InternalError,而不是将'constructor'设置为实例属性。 –

+0

thx,我已经更新了示例以在原型中包含构造函数。 –

+0

@ gion_13似乎你仍然在使用'InternalError.constructor = InternalError;'而不是'InternalError.prototype.constructor = InternalError' – Leonardo

-3

扩展错误对象(和一般的主机对象)在所有的浏览器不工作Error.prototype甚至不存在。 。在IE浏览器没有必要虽然,延长Error对象只是使用的自定义对象就行了,即使对象文本:{message: 'Really bad error}

+1

-1 for *“'Error.prototype'甚至不存在于IE”*,这是不正确的。另外,'Error'不是主机对象。即使这样,IE自从IE 8以来,已经为大多数主机对象制作了'prototype'原型。在所有实现ECMA-262第3版的浏览器中,应该可以扩展Error对象。 –

+1

-1代表错误 – Raynos