JavaScriptでリフレクションって、どんな感じだろう?
ひとまずnew演算子を直接指定しないで、インスタンスを取得する感じを
グローバルスコープ限定で適当に書いてみたけど、
使い道があんまり思いつかない。
Snipplrref
Posted by inamorix on December 4th, 2007
- String.prototype.ref = function () {
- for (var args = [], i = 0; i < arguments.length; i++)
- args.push('arguments[' + i + ']');
- if (window[this] && window[this] instanceof Function)
- return eval('(new window.' + this + '(' + args.join(',') + '))');
- throw new Error('Function window.' + this + ' does not exist.');
- };
function test () {
this.fn = function () { return 'hello'; };
}
こんな関数があったとして、
str = 'test'; str.ref().fn(); // 'hello'
文字列からインスタンスを生成、そのままメソッドコール。
str = 'Array'; str.ref(1, 2, 3).length; // 3
配列とかも出来るかな。
他は全然チェックしていない。