user2381011
user2381011

Reputation: 351

OOP JavaScript - public variable undefined

I'm having a problem with the scope of a public variable in javascript. The variable is declared in the main function (function Level) of my javascript class. The loadXML function is called from outside the class, but knows the this.layers variable. When my xml is loaded and redirected to another function the this.layers variable suddenly is undefined. Anyone having experience with this kind of problem.

var Level = (function()
{

function Level()
{
    this.layers = 3;
}

Level.prototype.loadXML = function()
{
    console.log(this.layers); //variable is defined!
    $.get("xml/level_" + this.currentLevel + ".xml", Level.buildGrid);
};

Level.buildGrid = function(xml)
{
    console.log(this.layers); //variable is undefined!
};

return Level;

})();

Thanks in advance.

Upvotes: 0

Views: 127

Answers (2)

Niccolò Campolungo
Niccolò Campolungo

Reputation: 12042

Return a new function from buildGrid that will be passed as jQuery's callback and pass to the wrapped function the current level so that you can get informations from the argument passed. The buildGrid function is so private to the Level's closure and can be accessed only inside it.

var Level = (function () {
    var buildGrid = function (level) {
        return function(xml) {
            console.log(xml);
            console.log(level.layers);
        };
    };
    function Level() {
        this.layers = 3;
    }
    Level.prototype.loadXML = function () {
        console.log(this.layers); //variable is defined!
        $.get("xml/level_" + this.currentLevel + ".xml", buildGrid(this));
    };
    return Level;
})();

Upvotes: 1

silicakes
silicakes

Reputation: 6902

this.layers only exists within the scope of level which is a constructur.

try the following:

var t = new Level.Level()
t.layers

Upvotes: 0

Related Questions