在我的網站,我使用存儲在文件「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()和打印結果),它是空的。
'返回this.tree [名]。兒童;'需要是'回報category.tree [名]。兒童;' –
@AlivetoDie你確定嗎?因爲'category'是基礎對象,所以我會說'return category.tree [name] .children'。 '樹'是未定義的。 –
哦,是的。感謝您告訴 –