我正在尝试在 JavaScript 中创建一个 Exception 类,尽管我已经使用 JavaScript 很长时间了,但我在原型设计方面遇到了一点问题,但我从未真正正确使用过原型设计
所以这是我的代码,
// load the Object Prototype
Exception = Object;
Exception.prototype = new function () {
// set defaults
this.name = "Exception";
this.message = "";
this.level = "Unrecoverable";
this.html = "No HTML provided";
// code so that the console can get the name from this.name insted of using [object Object]
this.getName = function(){
return this.name;
}
// this is the exec of the object prototype the code that is executed when the new Exception call is made
this.exec = function(msg, name, lvl, html){
// create a return variable
var ret;
// check that msg is defined and is not empty
if(typeof(msg) == "undefined" || msg == ""){
throw new Exception("Can't throw exception without a msg");
}
// set up this Exception Object values
this.name = (typeof(name) == "undefined")? this.name : name;
this.level = (typeof(lvl) == "undefined")? this.level : lvl;
this.message = msg;
this.html = (typeof(this.html) == "undefined")? this.html : html;
// delete the getName function so it does not get set though to the console
delete this.getName;
// save the Exception object to our return variable
ret = this;
// re add the getName object to the Exception Object so that it can be called from the console
this.getName = function(){
return this.name;
}
// return the saved Exception object without the getName method
return ret;
}
}
但由于某种原因在控制台中它返回作为参数给出的字符串msg
这是我收到的控制台输出
throw new Exception("test");
test
0: "t"
1: "e"
2: "s"
3: "t"
length: 4
__proto__: String
任何帮助将不胜感激