2017-10-09 122 views
0

在我的網站,我使用存儲在文件「categories.json」 JSON對象類別樹。它的值被存儲爲名爲「category」的對象的屬性「tree」,以及用於訪問它的一些方法。這是部分代碼:變量jQuery.getJSON回調內部設置不保留其價值

var category = { 

    tree: {}, 

    // loads the tree into memory 
    loadTree: function() { 
     $.getJSON("categories.json", function(data) { 
      this.tree = data; 
      console.log("Tree loaded"); 
     }); 
    }, 

    // Returns an array with the children of a node 
    getChildren: function(name) { 
     return this.tree[name].children; 
    } 

    ... 
} 

我明白,既然是的getJSON異步函數,回調的,我作爲一個參數傳遞的效果不會立即生效。但是,即使在「加載樹」消息已被示出,每當我訪問category.tree對象(即主叫category.getChildren()和打印結果),它是空的。

+0

'返回this.tree [名]。兒童;'需要是'回報category.tree [名]。兒童;' –

+0

@AlivetoDie你確定嗎?因爲'category'是基礎對象,所以我會說'return category.tree [name] .children'。 '樹'是未定義的。 –

+0

哦,是的。感謝您告訴 –

回答

1

this並非指什麼。你在category對象內,因此,你必須參考它。

this纔有意義,如果你是一個類的實例裏面,但是這只是一個普通的對象。

var category = { 
 

 
    tree: {}, 
 

 
    // loads the tree into memory 
 
    loadTree: function() { 
 
     category.tree = { foo : "bar" } 
 
    }, 
 

 
    // Returns an array with the children of a node 
 
    getChildren: function(name) { 
 
     return category.tree 
 
    } 
 

 
} 
 

 
category.loadTree() 
 
console.log(category.getChildren()) // { foo : "bar" }

用類,其中使用this同樣的事情是有意義的:

class Category { 
 

 
\t constructor(){ 
 
\t  this.tree = {} \t 
 
\t } 
 
\t 
 
    // loads the tree into memory 
 
    loadTree() { 
 
     this.tree = { foo : "bar" } 
 
    } 
 

 
    // Returns an array with the children of a node 
 
    getChildren(name) { 
 
     return this.tree 
 
    } 
 

 
} 
 

 
const category = new Category() 
 
category.loadTree() 
 
console.log(category.getChildren())

+0

謝謝,它工作! – Sponja