2017-10-09 121 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