リフレクション
Javaではよくリフレクションを使いますが、javascriptでも同様に出来ました。
Java
public class User { private String name; private int age; User(String name, int age) { this.name = name; this.age = age; } public int getAge() { return age; } public String getName() { return name; } public static void main(String[] args) throws Exception { User taro = new User("太朗", 26); Method[] methods = User.class.getMethods(); for (Method method : methods) { if (!method.getName().startsWith("get")) continue; Object value = method.invoke(taro, null); System.out.println(value); } } }
javascript
var User = function(name, age){ this.name = name; this.age = age; } User.prototype.getName = function() { return this.name; } User.prototype.getAge = function() { return this.age; } var taro = new User('太朗', 26); for(var property in taro) { var method = taro[property]; if ( typeof method != 'function' ) continue; if ( !property.match('get.*') ) continue; var value = method.apply(taro, null); console.log(value); }
javascriptの方は、メソッドだけ取得することは出来ないので、関数意外は除外するっていうのが入ってます。
上の例はjavaを意識して書きましたが、実はjavascriptはもっと直感的に書けます。
var value = method.apply(taro, null); ↓ var value = method();
こんな感じ〜。
覚えておくと役立つかも。