使用 underscore.js 创建 javascript 自定义错误对象的快捷方式?
有没有一种干净的方法以某种方式使用 underscore.js _.extend 函数(或任何其他函数)来创建从基 Error 类继承的自定义 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;
但它不起作用:(。
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 :(.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(请原谅我关于原型继承的小括号。您可以跳过此部分并查看下面的答案。
为了让一个对象扩展另一个对象,
子
的原型必须是您可以在网上找到许多关于此的好资源,但不幸的是,也有很多不好的资源,因此我建议您阅读这篇文章:http://javascript.crockford.com/prototypal.html 。通过
new
关键字实例化的新对象:new f()
返回其原型对象的副本:f.prototype.承认这一点,您意识到为了扩展对象
x
,当前对象的原型必须是一个新的 x 实例:)
您实际上不需要 underscore.js那:
如果你真的想使用 underscore.js :
(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
new
keyword :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 :
扩展错误对象(以及一般的主机对象)并不适用于所有浏览器。
Error.prototype
在 IE 上甚至不存在。不过,无需扩展Error
对象,只需使用任何自定义对象即可,甚至是对象文字:{message: 'Really bad error}
。Extending the error object (and host objects in general) does not work in all browsers.
Error.prototype
doesn't even exist on IE. There is no need to extend theError
object though, just using any custom object will do, even object literals:{message: 'Really bad error}
.