次のようなカスタム Javascript オブジェクトがあります。
var CustomClass = function(settings) {
this.var_1 = false;
this.var_2 = null;
this.var_3 = 0;
}
CustomClass.prototype.method_1 = function(){
var reader = new FileReader();
reader.onload = (function(cropWidget) {
this.var_1 = true;
});
}
CustomClass.prototype.method_2 = function(){
console.log(this.var_1); // logs 'false' onto the console
if(this.var_1)
{ // proceed further and do something
}
}
CustomObject は以下でインスタンス化されます。
$(document).ready(function{;
var customObj = new CustomClass({/*json values*/});
});
そして、別の DOM イベントが次のように method_1 を呼び出します。
$('#element1').click(function(){
customObj.method_1(); // this is where var_1 is being set to true
});
次のように、method_2() が別の要素によって DOMで呼び出されると、問題が発生します。
$('#element2').click(function(){
customObj.method_2();
});
customObj がmethod_1 を呼び出したときに true に設定されていたvar_1 の値をチェックします。
this.var_1 は false であり、本来あるべき true ではありません。これは、var_1 のスコープが method_1() のスコープに対してのみ true に設定され、古い値を保持していることを意味しますか? IMO Javascript は参照渡しであるため、変数の値は元の場所で true に設定する必要があります。
私が間違っている場所と、var_1 の値を method_2 でも新しい値を保持するように設定する方法を誰かが説明できますか?