2016-04-09 3 views
0

Я новичок в ООП в JS. Прямо сейчас я пытаюсь вызвать переменную в экземпляре, но как я могу назвать ее в функции?JavaScript Функция Функция Доступ Переменная в setTimeout

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); 

ответ

0

Просто хранить this в переменной перед функцией:

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); 

В качестве альтернативы, вы можете использовать ES6 Новинки arrow functions в зависимости от требований проекта:

window.setTimeout(() => { 

    console.log(this.a);  

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

Спасибо! Это отлично работает для меня! –