メソッドに動的にアクセスしたい
引き続きオワタcheckboxネタで、みかぽんからQAが出たネタを。
if文でメソッドをハンドリングしたい時なんかに使う手だが、変数に入っている文字列値をメソッドとしてコールしたい場合、phpなんかだと
$method=($state)?"print":"store"; $this->$method; /* $this->print() か$this->store()がコールされる*/
で済むわけだが、javascriptの場合、
method=(state)?'print':'store'; this.method(); /* methodがコールされてしまう */ or this.method; /* methodというメソッドのfunctionオブジェクトをさしてしまう */
とかでこのままではダメ。では、どうするかっていうと配列へのアクセスのように[]でくくる。
this[method](); /* methodが評価される */
NackyのオワタjQuery版を勝手に添削すると
$(this).click(function(){ (this.checked)?$(this).parent().find(".owataface").show():$(this).parent().find(".owataface").hide(); }); ↓ $(this).click(function(){ $(this).parent().find(".owataface")[(this.checked)?'show':'hide')](); });
と書くことができる。「this.hoge()」と「this['hoge']()」は等価なのですね。
動的にメソッド指定するときにいろいろラクである。