Search code examples
javascriptprototypejs

Javascript class calling a function within a function


function ObjectProvider() {
    this.url = "ajax/inbounds.php"
    this.inBounds = function () {
        this.removeMarkers();
        var url_string = this.url;
        $.getJSON(url_string, function (data) {
            for (i = 0; i != data.length; ++i) {
                this.createObject(data[i]);
            }
        });
    };
    this.createObject = function (_data) {};
    this.removeMarkers = function () {};
};

So the line

this.createObject( data[i] );

is having some issues, but

this.removeMarkers();

works fine.

Both functions are defined in the ObjectProvider object. Have tried adding a function called test() and just doesn't like anything being called within the JSON callback function.


Solution

  • This is a typical scoping problem; the this inside your $.getJSON() callback function is no longer the same this.

    To resolve the problem, you have to keep a reference to this before calling $.getJSON(), e.g.

    var self = this;
    $.getJSON(url_string, function(data) {
        // self.createObject( data[i] );
    });
    

    Or, bind the success callback function using $.proxy:

    $.getJSON(url_string, $.proxy(function(data) {
        this.createObject(data[i]);
    }, this));