log.metatype

Reflection of JavaScript

JavaScriptでリフレクションって、どんな感じだろう?
ひとまずnew演算子を直接指定しないで、インスタンスを取得する感じを
グローバルスコープ限定で適当に書いてみたけど、
使い道があんまり思いつかない。

Snipplrref

Posted by inamorix on December 4th, 2007

  1. String.prototype.ref = function () {
  2.         for (var args = [], i = 0; i < arguments.length; i++)
  3.                 args.push('arguments[' + i + ']');
  4.         if (window[this] && window[this] instanceof Function)
  5.                 return eval('(new window.' + this + '(' + args.join(',') + '))');
  6.         throw new Error('Function window.' + this + ' does not exist.');
  7. };


function test () {
	this.fn = function () { return 'hello'; };
}

こんな関数があったとして、

str = 'test';
str.ref().fn(); // 'hello'

文字列からインスタンスを生成、そのままメソッドコール。

str = 'Array';
str.ref(1, 2, 3).length; // 3

配列とかも出来るかな。
他は全然チェックしていない。

Post a comment