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
どんな助けでも大歓迎です