JavaScript ã® getter/setter ã«ã¤ãã¦
JavaScript 㧠getter/setter ã使ããã¨ãããã¨ãä»æ´ãªããç¥ã£ããåã ECMAScript ãã¼ã¹ã® ActionScript ã¯ä½¿ããã®ã«ãªã¼ãã¨æã£ã¦ããæ¡ã®å®ä½¿ãããã¯ããç§ã®ä¸åå¼·ã§ããããã
åèï¼
- いろんな言語のSetter・Getterを比較してみた at HouseTect, JavaScriptな情報をあなたに
- IE 以外の JavaScript で getter setter が使えるようになる! - IT戦記
ããããã»ã¨ãã©ä½¿ã£ã¦ãã®ãè¦ããã¨ããªããããããªã©ã¤ãã©ãªã§ã¯é度ãéè¦ããããããï¼ã¨ãæã£ãããã©ã¤ãã©ãªã ãããããããããã¢ã¯ã»ããµã¡ã½ããã¯éè¦ãªããããªãã ãããã
IEã§ã¯éãµãã¼ããªã®ã§æå³ãªãã¨ãããã¨ãããããªããããï¼ããä¸å¿å¯¾å¿çã¯ããï¼
ã¨ãããããã©ããããé ãã®ã測ã£ã¦ã¿ããã¨ã«ããã
ãããªãªãã¸ã§ã¯ããä½ã£ã¦ãç´æ¥ã¢ã¯ã»ã¹ãgetter/setter ã¢ã¯ã»ã¹ã®å®è¡æéãæ¯ã¹ã¦ã¿ãã
var Test = { a: 10, _num: 1, _str: 'hoge', _obj: {i: 1}, get num() { return this._num; }, set num(n) { this._num = n; }, get str() { return this._str; }, set str(s) { this._str = s; }, get obj() {return this._obj; }, set obj(o) { this._obj = o; }, };
ãªããè¨æ¸¬ã¯ãããªæãã
function calcTime(count, fn){ var d = new Date().getTime(); for(var i=0; i<count; i++){ fn(); } var pd = new Date().getTime(); return (pd - d); } function start(){ var aGetTime = calcTime(count, function(){ var a = Test.a; }); var aSetTime = calcTime(count, function(){ Test.a = 100; }); ã»ã»ã»
ãªãã FireFox(3.6.13)ã§ã¯åããããã
Safari 5.0.3 㨠Chrome 9.0 ã§è©¦ãã¾ãããã«ã¼ãåæ°ã¯10000åã§ãä½åãåããå¹³åçãªæéï¼msï¼ã§ãã
é ç® | Safari | Chrome |
Test.a get | 38 | 71 |
Test.a set | 35 | 70 |
Test.num get | 47 | 145 |
Test.num set | 53 | 149 |
Test.str get | 47 | 145 |
Test.str set | 54 | 150 |
Test.obj.i get | 47 | 147 |
Test.obj.i set | 64 | 158 |
Safari ã¯ãã£ï¼ï¼ããããã£ã¢ã¯ã»ã¹ã¨ã¡ã½ããå¼ã³åºãã¯ã»ã¨ãã©éãããã¾ãããChromeã®ã»ãã¯ã大ä½åãããã«ãªã£ã¦ã¾ããããããã¾ãã10ä¸åã¢ã¯ã»ã¹ã§ãããªãã®ãªã®ã§é常ã¯ã»ã¨ãã©èª¤å·®ã§ããã
ã¨ããããã§ãç©æ¥µçã«ä½¿ã£ã¦ãããã¨æãã¾ãã
ãªããå½æ¹ã®ç°å¢ã¯ MacBook Air11"(OS X 10.6.6) ã§ãã
ã¾ãããããæ¯åæã¤ã®ã¯ããã©ãããã®ã§ãObjective-C ã® @synthesize ã¨ãã¿ããã«ã§ããªãããªãã¨æã£ã¦ä½ã£ã¦ã¿ããruby ã®ããã§ããã
function attr_accessor(obj, name, initialValue){ var pname = "_" + name; obj.prototype[pname] = typeof initialValue === 'undefined' ? null : initialValue; obj.prototype.__defineGetter__(name, function() { return this[pname]; } ); obj.prototype.__defineSetter__(name, function(val) { this[pname] = val; } ); }; // 使ãæ¹ TestObj = function(){ }; // ãªãã¸ã§ã¯ãã«ããããã£ã¨Getter/Setterãåæå¤ãä»ããã attr_accessor(TestObj, 'foo', 'Hello Accessor!'); var o = new TestObj(); alert('o.foo: ' + o.foo);
ããã§ããããã£ãã°ã£ã¡ãé è½ï¼ o._foo ã¨ãã§ã¢ã¯ã»ã¹ã§ãã¡ãããã©ãã¾ããªãããããã ãã
ããããä½ã£ã¦æã£ãããããã¾ãæå³ãªããªãå¾®å¦ããã