javascript - jQuery.getJSON 回调中设置的变量不会保留其值

标签 javascript jquery json ajax

在我的网站中,我使用作为 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/

相关文章:

javascript - 查找函数参数的数量及其名称

javascript - gulp 在 gulp-load-plugins 错误中加载其他模式

javascript - 谷歌地图多段线重叠困境

java - 尝试将 Object 转换为 MapEntry 时出现 ClassCastException

php - 使用 POST 方法和 HttpURLConnection 将 JSON 对象从 Android 发送到 PHP 服务器

php - 使用 json_encode 方法将 PHP 数组传递到外部 Javascript 函数中,结果为 'undefined'

javascript - 无法在回调 AngularJS 中访问 JSON 响应

javascript - 对象在 panel.port.on 上返回两次

javascript - 重写 JQuery 函数(日志装饰器)

javascript - jstree 触发排序插件