2016-04-09 22 views
0

JS'de OOP'ta bir yeni üyeyim. Şu anda, örnekte değişkeni aramaya çalışıyorum, ancak bunu işlevde nasıl arayabilirim?JavaScript Nesne İşlev Erişim setTimeout içinde değişken

var foo = function() { 

    this.a = 1; // how can I call 'a' in the setTimeout() function 

    this.start = function(i) { 
     if (i<3){ 
      window.setTimeout(function() { 

       console.log(a); // this line shows undefined 
       console.log(this.a);  // this line indicates 'this' is window 

       i++; 
       start(i); // this one does not work as well 

      }, 2000); 
     } 
    }; 
}; 

var bar = new foo(); 
bar.start(0); 

cevap

0

Sadece işlevi önce bir değişkende this saklamak:

var foo = function() { 

    this.a = 1; // how can I call 'a' in the setTimeout() function 

    this.start = function(i) { 
     var that = this; 
     if (i<3){ 
      window.setTimeout(function() { 

       console.log(that.a);  

       i++; 
       that.start(i); // this one does not work as well 

      }, 2000); 
     } 
    }; 
}; 

var bar = new foo(); 
bar.start(0); 

Alternatif olarak, proje gereksinimlerine ES6 yeni arrow functions bağlı kullanabilirsiniz:

window.setTimeout(() => { 

    console.log(this.a);  

    i++; 
    this.start(i); // this one does not work as well 
}, 2000); 
+0

teşekkür ederiz! Benim için mükemmel çalışıyor! –

İlgili konular