我試圖通過原型Error構造的延伸擴展JavaScript錯誤性質:擴展本地JavaScript錯誤構造
<script type="text/javascript">
// extending the Error properties to all the ones available in the various browsers:
Error.prototype = {
name: null, // (all browsers); the name of the error
message: null, // (all browsers); the error message as a string
description: null, // (Internet Explorer); description of the error
fileName: null, // (Firefox); the name of the file where the error occurred
lineNumber: null, // (Firefox); the number of line where the error occurred
columnNumber: null, // (Firefox); the number of column where the error occurred
number: null, // (Internet Explorer); the error code as a number
stack: null // (Firefox, Chrome); detailed information about the location where the error exactly occurred
};
function log(error) {
var errors = [];
for (var prop in error) {
errors.push(prop + ': ' + error[prop]);
}
alert(errors.join('\n'));
}
</script>
然後我測試日誌功能:
<script type="text/javascript>
try {
var a = b; // b is undefined!
} catch(error) {
log(error);
}
</script>
的結果是錯誤對象只顯示一些屬性(例如,在Firefox fileName
,lineNumber
和columnNumber
),如果它沒有被擴展。
但最奇怪的是,for...in
週期似乎無法行走的所有錯誤對象屬性:試圖提醒標準屬性error.message
正常返回的消息。
所以我測試的結果是:
- Error構造不是通過其原型可擴展的,其他原生構造函數;
for...in
循環無法行走錯誤對象的屬性。
對嗎?
是否有一些有趣的證據/資源可能會建議您更多地瞭解它?
'Error'是一個宿主對象,因此不必像JavaScript的「普通」對象那樣工作。 –
嗯,有趣,我不知道主機對象。我通過Stackoverflow線程學習了一些東西。至於現在,我知道它們是具有特殊屬性和行爲的特殊對象,比如DOM對象,我說得對嗎? –
請參閱http://es5.github.com/#x4.3.8。如果您在本網站上搜索「主機對象」,您會發現一些關於它們的有趣聲明。*編輯*:它們基本上是對象提供的環境而不是規範的一部分(就像DOM對象一樣,是的)。但問題可能只是'Error.prototype'不可寫(至少在Firefox中)。 'var obj = {foo:'bar'}; Error.prototype = obj; Error.prototype == obj;'產生'false'。 –