LoginSignup
11
12

More than 5 years have passed since last update.

動的に変数やメソッドを呼ぶ

Last updated at Posted at 2015-03-13
var o = {
  x: function(){return 1},
  y: function(){return 2},
  z: 'i am value'
};

o.x(); //=> 1
o.y(); //=> 2
o.z;   //=> 'i am value'
o['x'](); //=> 1
o['y'](); //=> 2
o['z'];   //=> 'i am value'

var a = 'x';
o[a](); //=> 1

グローバル空間っぽいところに作成された変数・メソッドも同様。

function a(){return 'hoge'}
var b = function(){return 'egoh'},
    c = 'hello (ツ)b';

this['a'](); //=> 'hoge'
this['b'](); //=> 'egoh'
this['c'];   //=> 'hello (ツ)b'
追記

大抵のjavascript style guideには以下のようなことが書いてあるようです。

// bad
o["x"];

// good
o.x;

必要がある時でなければ、メンバへのアクセスはgoodのようなやり方を使いましょう。

this['anyVar']のように書いたはいいけど、ソースをminifyした時に変数の名前が変わってしまい…みたいな事故が起こりえます。程々にしましょう。

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12