Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript this returns unknown property

I just wrote that piece of code and get an error at the alert part telling me, that this.words is not definded. I guess the jquery part changes the "this" value, because at where the comment is, I can access the array.

Now I stuck, because I don't want to make the words property global (what makes it run). So I want to ask you for a way to fix the problem while keeping in "OOP" style.

function game()
{
    this.difficulty = 0;
    this.mode = 0;
    this.words = new Array();

    this.loadWords = function()
    {
        //request word pool
        $.ajax({
            type:"GET",
            url:"word.php",
            data:{mode:this.mode, difficulty:this.difficulty}
        }).done(function(html) {
            alert(this.words.length);
        });
    }
}
like image 891
ltsstar Avatar asked Mar 27 '26 15:03

ltsstar


1 Answers

This appears to be a scoping issue. this no longer refers to the game object within the .done function. Try

this.loadWords = function()
{
    var that = this;
    //request word pool
    $.ajax({
        type:"GET",
        url:"word.php",
        data:{mode:this.mode, difficulty:this.difficulty}
    }).done(function(html) {
        alert(that.words.length);
    });
}
like image 100
jackwanders Avatar answered Mar 29 '26 04:03

jackwanders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!