0

My code looks like this:

function A() {
    this.AFunction = function() {
        var b = new B();
        b.BFunction();
    }
}

function B() {
    this.BFunction = function() {
         // some code
         $.ajax({ url: url
             success: BSuccess,
             // and so on
         })
    }

    this.BSuccess = function() {
         // some code
         this.anotherBFunc();
    }

    this.anotherBFunc = function() {
         // some code
    }
}

a = new A();
a.AFunction();

And it fails on the calling anotherBFunc. Could please some one help me understand why does it happed?

vminof
  • 121
  • 7

1 Answers1

1

To maintain scope you can use jQuery's proxy

success: $.proxy(this.BSuccess,this),

or with modern day browsers you can use bind

success: this.BSuccess.bind(this),
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • By "modern day", you mean "any browser anyone is actually using" http://kangax.github.io/es5-compat-table/#Function.prototype.bind :) – Chris Baker Apr 11 '14 at 17:27
  • People still use IE8 I am afraid and it is not modern. – epascarello Apr 11 '14 at 17:30
  • Only estimated at 10% of the global internet, there comes a point... http://theie8countdown.com/ – Chris Baker Apr 11 '14 at 17:35
  • Global !== Company's User Base. – epascarello Apr 11 '14 at 17:45
  • Okay, you win: Internet Explorer 8 has a great future, and is worth paying money to support indefinitely. The cost:benefit analysis heavily favors not only targeting the browser exclusively, but we should all go buy Microsoft stock on the strength of that software alone. :P – Chris Baker Apr 11 '14 at 17:56