代码之家  ›  专栏  ›  技术社区  ›  Aleksa Ristic

从ajax在javascript类中分配字段[duplicate]

  •  0
  • Aleksa Ristic  · 技术社区  · 8 年前

    我有这样的代码:

    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;
        }
    }
    

    我将这个类初始化为 let myClass = new Korisnik(1);

    当我试图 naziv() 它什么也不返回。我已经测试过了 alert this.IME 从内部 success 代码有价值,但在外部没有。我已经从 this question 但由于某种原因,那里的一切都不起作用。怎么办?

    1 回复  |  直到 8 年前
        1
  •  -1
  •   Joey Ciechanowicz    8 年前

    Js getter不是函数,所以需要作为 myClass.naziv

    你的另一个问题是 success 函数不是以相同的方式运行的 范围 作为你剩下的工作。

    可以使用fat arrow函数来确保范围正确。

           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