簡體   English   中英

為什么程序不調用js類函數?

[英]why the program doesn't call the js class function?

我在JS中有一個類,其中包含一系列與登錄名和用戶注冊有關的方法。 這些方法基本上可以捕獲頁面的事件,並且可以執行某些操作。

當創建UsersOperations()的實例時,它被稱為(由於click事件) $("#login").click(function(){}); ,正確執行...直到調用saveUserInfo();為止saveUserInfo(); ,至此,頁面已重新加載,我不知道為什么,我不明白,我有相同的方法,但沒有類,並且一切正常。

請幫助我,否則我將死於這個生存問題。

$(document).ready(function(){
  new UserOperations();
});

  class UserOperations{
    constructor() {
      if(!this.checkUserWithLogin())
        this.addLoginAndRegisterButtons();
      var self = this;
      $("#Log_In").click(function(){
        $.ajax({
          type: "GET",
          url: "php/request.php",
          async: true,
          data: {nick_log:$("#username").val(),
                  pass_log:$("#userpass").val()},
          success: function(data){
          var dataJson = JSON.parse(data);

          if(dataJson==null)
            alert("You are not registered");
          else {
            if($("#Keep_log").is(':checked')) 
              self.saveUserInfo(dataJson,"localStorage"); 

            else 
              self.saveUserInfo(dataJson,"sessionStorage"); 
            self.checkUserWithLogin();
          },
          error: function (obj, error, objError){
            alert("There is an error!");
          }
        });
      });
   }
}

因為this不再引用對象,所以找不到函數。 附加為回調的函數不會關閉this函數。 您可以使用另一個變量,例如var self = this; 或者您可以使用Function.prototype.bind()綁定回調。

這是一些使答案更完整的示例代碼,顯示了三種保留上下文的不同機制。 這些方法的根本需求是,在創建回調函數時,我們不會自動保留定義回調函數的方法中存在的this的值。 我們需要一些機制來在適當的對象上執行功能:

function Cat(name) {
    this.name = name;

    // Note we don't need anything special when we're immediately executing:
    console.log("Immediate execution with this:");
    this.speak();

    // Option 1. Explicitly specify the value of 'this' inside the callback using bind()
    setTimeout(function () {
        console.log("Callback execution with bind:");
        this.speak();
    }.bind(this), 1000);

    // Option 2. Copy 'this' into a local variable which is then captured in a closure
    var self = this;
    setTimeout(function () {
        console.log("Callback execution with closure variable:");
        self.speak();
    }, 2000);

    // Option 3. (ES6) Use a lambda/arrow function which does preserve the value of 'this' from the context in which it was defined
    setTimeout(() => {
        console.log("Lambda preserves the value of this:");
        this.speak();
    }, 3000);

}

Cat.prototype.speak = function () {
    console.log(this.name + " says meow!");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM