Search code examples
javascriptnode.jsclass-method

call methods in callback


I have this Try class:

function Try () {
  console.log('Start')
  this.Something( function() {
    console.log('asd')
    this.Some()
  })
}
Try.prototype.Something = function (callback) {
  console.log('hi all')
  callback()
}
Try.prototype.Some = function () {
  console.log('dsa')
}

But when I try to call the Some method in the callback part, it gives me an error, which says this.Some is not a function. What is the problem? How can i fix this?


Solution

  • scope of this is different inside a different function, even if it is inner function

    you need to preserve this of outer function in self and make it

    function Try () {
      console.log('Start')
      var self = this;
      self.Something( function() {
        console.log('asd')
        self.Some();
      })
    }