在我的网站中,我使用作为 JSON 对象存储在文件“categories.json”中的类别树。它的值存储为名为“category”的对象的属性“tree”,以及一些访问它的方法。这是代码的一部分:
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 是一个异步函数,因此我作为参数传递的回调的效果不会立即发生。然而,即使在显示“Tree returned”消息之后,每当我访问category.tree对象(即调用category.getChildren()并打印结果)时,它都是空的。
最佳答案
this
不指代任何内容。您位于 category
对象内部,因此,您必须引用它。
this
如果您位于 Class 实例中,则有意义,但这只是一个常规对象。
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 {
constructor(){
this.tree = {}
}
// 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() )
关于javascript - jQuery.getJSON 回调中设置的变量不会保留其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46646072/