2

I'm new to JS and the script I'm writing requires that I use ajax to retrieve JSON data from an API. This means I'm having to get my head around callbacks etc.

My objective with the simplified below code is to invoke a function (MethodA) which then invokes MethodB, which calls MethodC on completion.

For some reason, MethodC fails to activate and I have no idea why.

See fiddle for live example: https://jsfiddle.net/Hoppertron/mtpem1r2/5/

(I know that I could probably use jQuery's deferred when().then() pattern, or ES6 Promises, but as a learning exercise I'm trying to get my head around the barebones way to do it.)

    var Item = function (prop1, prop2, prop3) {
      this.prop1 = prop1,
      this.prop2 = prop2,
      this.prop3 = prop3,
      this.prop4; //<----------------- Notice I'm not setting this yet.
    };            //                   I'm setting it in MethodB.
                  //                   Is this stupid?


    Item.prototype.MethodA = function() {
      console.log("starting A")
      this.MethodB(function () {this.MethodC}); //<----- Why doesn't MethodC run?
    };

    Item.prototype.MethodB = function(callback) {
      console.log("starting B")
      this.prop4 = "I'm prop 4";
      console.dir(this);
      callback();
    };

    Item.prototype.MethodC = function () {
      console.log("starting C")
      document.getElementById("MainDiv").innerHTML = this.prop4;
    };

    var MyItem = new Item("I'm prop 1","I'm prop 2","I'm prop 3");

    try {
        MyItem.MethodA(); //<-- Should call MethodA which calls MethodB which calls MethodC
      }
      catch(err) {
        document.getElementById("MainDiv").innerHTML = err;
      };
Hoppertron
  • 166
  • 3
  • 9
  • 2
    When `callback()` calls the function that wraps `this.MethodC`, you're losing the context of `this`. The dupe explains ways of fixing it. (You're also missing the parentheses after `MethodC`, ie `this.MethodC()`) – James Thorpe Feb 10 '16 at 13:07

0 Answers0