@rogiivs

Как обратиться к this конструктора?

Как обратиться к this конструктора из вложенной функции?
вот код:
function Constr() {
    this.my = this;
    this.onStart = function () {
        console.log('start');
    };
    this.func = function () {
        navigator.getUserMedia({audio: true}, function (stream) {
            this.onStart(); // Не работает 
            my.onStart()    // Не работает
            },
            function (error) {

            });
    }
}
  • Вопрос задан
  • 104 просмотра
Решения вопроса 2
potapchino
@potapchino
для таких вот случаев и были сделаны arrow function. и не нужно заниматься ерундистикой с сохранением контекста, там где это не требуется:
function Constr() {
  this.onStart = function() {
    console.log('start')
  }
  
  this.func = function() {
    navigator.getUserMedia({ audio: true }, stream => {
      this.onStart()
    }, function(error) {
      
    })
  }
}
Ответ написан
@MadridianFox
Web-программист, многостаночник
function Constr() {
    let self= this; // <<<<<<<<<<<<
    this.onStart = function () {
        console.log('start');
    };
    this.func = function () {
        navigator.getUserMedia({audio: true}, function (stream) {
            self.onStart()  // <<<<<<<<<<<
            },
            function (error) {

            });
    }
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы