2008/11/06(木)javascriptのprototypeではまった
微妙にはまった罠
A = function(){}
A.prototype = {
data: new Array(),
push: function(a){
this.data.push(a);
},
pop: function(){
return this.data.pop();
}
}
a = new A();
b = new A();
a.push('1st');
a.push('2nd');
b.push('3rd');
a.pop(); // -> '3rd'
b.pop(); // -> '2nd'
a.pop(); // -> '1st'
当然と言えば当然だけど、ポインタ的なものが見えにくいので原因がわかるまで時間がかかりました。というか、C++のクラスとJavascriptのプロトタイプの違いがわかった気がする。正しくは↓の通り。
A = function(){
this.data = new Array();
}
A.prototype = {
data: null,
push: function(a){
this.data.push(a);
},
pop: function(){
return this.data.pop();
}
}
a = new A();
b = new A();
a.push('1st');
a.push('2nd');
b.push('3rd');
a.pop(); // -> '2nd'
b.pop(); // -> '3rd'
a.pop(); // -> '1st'
オブジェクトを生成するたびに data そのものを正しく初期化する必要あり。