Tell me what's wrong. After accessing the prototype of Weather.geton error “is not a function” is displayed. In the functional style, everything works without errors.

  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 } 
  • one
    this inside xhr.onload = function() { not the same as outside - Grundy
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

this inside the onload handler references an XMLHttpRequest object, and it does not have the methods successH and errorH .

You can fix it for example by saving the link to the desired object before onload and using it instead of this , for example

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

Or use the arrow functions from 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(); } 

Another option with 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(); } 
  • @PavelMayorov, fixed :) - Grundy
  • Thank you very much, everything works! - Dmitriy Morgul