这篇文章:http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/
说你可以这样做:
function MyError(message){
this.message=messsage;
this.name="MyError";
this.poo="poo";
}
MyError.prototype = new Error();
try{
alert("hello hal");
throw new MyError("wibble");
} catch (er) {
alert (er.poo); // undefined.
alert (er instanceof MyError); // false
alert (er.name); // ReferenceError.
}
但它不起作用(得到“未定义”和错误)
这甚至可能吗?
答案 0 :(得分:2)
Douglas Crockford建议抛出这样的错误:
throw{
name: "SomeErrorName",
message: "This is the error message",
poo: "this is poo?"
}
然后你可以很容易地说:
try {
throw{
name: "SomeErrorName",
message: "This is the error message",
poo: "this is poo?"
}
}
catch(e){
//prints "this is poo?"
console.log(e.poo)
}
如果你真的想使用MyError Function方法,它应该看起来像这样:
function MyError(message){
var message = message;
var name = "MyError";
var poo = "poo";
return{
message: message,
name: name,
poo: poo
}
};