4

エラー コンストラクターのプロトタイプを拡張して、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しますlineNumbercolumnNumber

しかし、最も奇妙なことは、for...inサイクルがすべてのエラー オブジェクト プロパティを処理できないように見えることです。標準プロパティを警告しようとすると、error.message通常はメッセージが返されます。

したがって、私のテストの結果は次のとおりです。

  1. Error コンストラクターは、他のネイティブ コンストラクターとは異なり、そのプロトタイプを通じて拡張できません。
  2. ループはfor...inエラー オブジェクトのプロパティをたどることができません。

私は正しいですか?
それについてもっと知るために提案できる興味深い証拠/リソースはありますか?

4

1 に答える 1