0

I have code like this:

class Korisnik
{
    constructor(korisnikId)
    {
        this.KORISNIKID = korisnikId;
        this.IME = "";
        this.UNIQUE_KEY = "";

        this.Initialize();
    }

    Initialize(kid)
    {
        $.ajax({
           type: "POST",
           url: "../Php/Korisnik_Get.php",
           data: {"korisnikId" : this.KORISNIKID},
           success: function(result)
           {
               var arr = result.split('|');
               this.IME = arr[0];
               this.UNIQUE_KEY = arr[1];
           }
        });
    }

    get naziv()
    {
        alert("IME: " + this.IME); //Undefined
        return this.IME;
    }
}

I initialize this class as let myClass = new Korisnik(1);

When I try to get naziv() It returns nothing. I have tested it and when I alert this.IME from inside success code it has value but outside it doesn't. I have read and tried from this question but anything from there is not working for some reason. What to do?

Aleksa Ristic
  • 2,069
  • 1
  • 13
  • 39
  • 1
    `this` inside the `$.ajax` success callback isn't what `this` is outside it. See the linked questions for answers (in this case: use an arrow function or `bind`). – T.J. Crowder Jul 24 '18 at 12:55

1 Answers1

-1

Js getters aren't functions, so you need to access it as myClass.naziv

The other problem you have is that your success function isn't running in the same scope as the rest of your function.

You can use a fat-arrow function to ensure you have the right scope.

       success: result =>
       {
           var arr = result.split('|');
           this.IME = arr[0];
           this.UNIQUE_KEY = arr[1];
       }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

Joey Ciechanowicz
  • 2,711
  • 3
  • 19
  • 45