0

次のようなカスタム 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 でも新しい値を保持するように設定する方法を誰かが説明できますか?

4

2 に答える 2

3

問題は、var_1trueに設定しているスコープが、希望するスコープではないことです。

CustomClass.prototype.method_1 = function(){

  var reader = new FileReader();
  reader.onload = function(cropWidget) {
    this.var_1 = true;
  };
}

コールバックでに設定var_trueていますが、コールバックのの値は。の値と同じでthisはありませんmethod_1

イディオムを使用してself = thisこれを修正できます。

CustomClass.prototype.method_1 = function(){
  // "this" here refers to the CustomClass instance,
  // so let's store it in "self" so we can use it in the callback
  var self = this; 

  var reader = new FileReader();

  reader.onload = function(cropWidget) {
    // "this" here will not be the CustomClass instance, 
    // so we refer to the "self" variable from above.
    self.var_1 = true;
  };
}

これで問題は解決するはずですが、タイミングの問題がまだ発生する可能性があります。イベントが発生するmethod_2前にが呼び出された場合、まだに設定されません。FileReaderonloadvar_1true

于 2013-02-08T20:44:31.713 に答える