JavaScript でリフレクションを利用する


JavaScript でリフレクションを利用してみた。肝は

arguments.callee.toString();

以下は、実行されているメソッド名を取得し、引数の数が正しくなければ、メソッド名と正しい引数を出力する例。

function hoge(a, b, c) {
var matches = arguments.callee.toString().match(/function\s+([^(]+\([^)]*\))/);
if (arguments.callee.length != arguments.length) {
console.log("Wrong number of arguments for : " + matches[1]);
}
}
hoge(1, 2);
//=> wrong number of arguments for : hoge(a, b, c)
カテゴリー: JavaScript   パーマリンク

コメントをどうぞ

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>