0

I'm having an odd error with a JS object, it goes like this:

function MatchManager(){
    this.current_m = [];
}

MatchManager.prototype.addMatchBatch = function (array){
    // yes I could do an apply..
    for(var i = 0; i < array.length; i++){
        this.current_m.push(array[i]);
    }
}

However, when I call addMatchBatch on an instance of MatchManager I get Cannot read property 'push' of undefined. Which means that current_m is not being recognized by the Instance.

I also tried adding var parent=this; and changing this by parent inside the for loop, to no avail.

I'm guessing this references the addMatchBatch function instead of the Instance... how do I overcome this?

If anyone has any idea why, I will be very grateful!

Thanks a lot!

PS: I'm calling and instantiating my objects like so:

MatchManager.prototype.getCurrent = function(){
    var options : {
        url : myUrl,
        method: "GET",
        callback: this.addMatchBatch
    };

    AJAXCall(options);
}

var manager = new MatchManager();
manager.getCurrent();
Jo Colina
  • 1,870
  • 7
  • 28
  • 46
  • 2
    Please show how exactly are you calling the function. – Teemu Nov 08 '15 at 18:04
  • 1
    … including how you create the instance. – Quentin Nov 08 '15 at 18:04
  • The function is being called from a callback on a XMLHttpRequest from another method of MatchManager, and the instanciation is simply `var manager = new MatchManager()` – Jo Colina Nov 08 '15 at 18:06
  • Don't vaguely describe how you are calling it. Provide a proper [test case](http://sscce.org/) so we can reproduce the problem. (I ran that code, made assumptions about how you were using it, and the problem you described did not occur). – Quentin Nov 08 '15 at 18:09
  • @Quentin added to the question ;) – Jo Colina Nov 08 '15 at 18:12
  • There's still no `.addMatchBatch` call in the post ... Notice, that setting `callback: this.addMatchBatch` assigns just a reference to `callback`, not context. You've to bind the context when you're actually calling the method. – Teemu Nov 08 '15 at 18:14
  • its the callback on AJAXCall, it is called when the response arrives – Jo Colina Nov 08 '15 at 18:15

1 Answers1

0
callback: this.addMatchBatch

You are passing the function as an argument, but the value of this inside it depends on the context in which it is called and whatever AJAXCall does, it isn't calling it in the first context.

Create a new function which calls it in the right context and pass that function instead.

callback: this.addMatchBatch.bind(this)
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335