0

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.

4
  • 4
    Looks like you mean to use Level.prototype.buildGrid = function() rather than Level.buildGrid... Commented Nov 2, 2013 at 12:48
  • I wanted the Level.buildGrid to be a private function, so I dropped the prototype which seems to work. Commented Nov 2, 2013 at 12:50
  • 1
    no this way what you did was making it a static function. If you want it private, declare it inside the constructor as a simple function, it will not be visible outside Commented Nov 2, 2013 at 12:52
  • you can also choose to name your function with a leading _, like _buildGrid, it is common for function that are public but should be treated as private Commented Nov 2, 2013 at 12:54

2 Answers 2

1

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;
})();
Sign up to request clarification or add additional context in comments.

Comments

0

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

try the following:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.