在我的网站,我使用存储在文件“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'。 '树'是未定义的。 –
哦,是的。感谢您告诉 –