1

Подскажите, что не так. После обращения к прототипу Weather.geton выдаётся ошибка «is not a function». В функциональном стиле всё работает без ошибок.

 function Weather(url) {
        this.geton(url);
        console.log(url);
    }

    Weather.prototype.geton = function(url) {
        var xhr = new XMLHttpRequest();
            xhr.open('get', url, true );
            xhr.responseType = 'json';
            xhr.onload = function() {
                var status = xhr.status;
                if (status === 200) {
                    this.successH(xhr.response);
                } else {
                    this.errorH(status)
                }
            }
            xhr.send();
        }

    Weather.prototype.successH = function(data) {
        if (typeof data == 'string') {
            return;
        } else {
        console.log(data);
        }
    }

    Weather.prototype.errorH = function(err) {
        return
    }
  • 1
    this внутри xhr.onload = function() { не тот же самый что снаружи – Grundy Apr 27 '16 at 14:26
  • Если вам дан исчерпывающий ответ, отметьте его как верный (галка напротив выбранного ответа). – Nicolas Chabanovsky Apr 27 '16 at 20:14

1 Answers1

1

this внутри обработчика onload ссылается на объект XMLHttpRequest, а у него нет методов successH и errorH.

Исправить можно например сохранив ссылку на нужный объект до onload и используя ее вместо this, например

Weather.prototype.geton = function(url) {

    var self = this,
        xhr = new XMLHttpRequest();

    xhr.open('get', url, true );
    xhr.responseType = 'json';
    xhr.onload = function() {
        var status = xhr.status;
        if (status === 200) {
            self.successH(xhr.response);
        } else {
            self.errorH(status)
        }
    }
    xhr.send();
}

Либо использовать стрелочные функции из ES2015

Weather.prototype.geton = function(url) {

    var xhr = new XMLHttpRequest();

    xhr.open('get', url, true );
    xhr.responseType = 'json';
    xhr.onload = () => {
        var status = xhr.status;
        if (status === 200) {
            this.successH(xhr.response);
        } else {
            this.errorH(status)
        }
    }
    xhr.send();
}

Еще вариант с bind

Weather.prototype.geton = function(url) {

    var xhr = new XMLHttpRequest();

    xhr.open('get', url, true );
    xhr.responseType = 'json';
    xhr.onload = function (){
        var status = xhr.status;
        if (status === 200) {
            this.successH(xhr.response);
        } else {
            this.errorH(status)
        }
    }.bind(this);
    xhr.send();
}
Grundy
  • 81,538