gpt4 book ai didi

javascript - 从回调内部访问对象字面量属性(异步方法)

转载 作者:数据小太阳 更新时间:2023-10-29 04:10:56 25 4
gpt4 key购买 nike

我正在编写一个需要与书签子树交互的 chrome 扩展。这个子树有很多交互,所以我将这个逻辑抽象成一个对象字面量,如下所示:

var contextStore = {
'root_id': undefined,
'setup': function() {...}, // populates root_id
'add': function(name) {...}, // uses root_id
'remove': function(name) {...}, // uses root_id
// ... etc ...
};

contextStore.setup(); // only once.
contextStore.add("foo");
contextStore.add("bar");
// ... etc

到目前为止,还不错。

我遇到的麻烦是由异步 Chrome API(以及我缺乏 JS-fu)引起的。即:

var contextStore = {
'root_id': undefined,
'setup': function() {
chrome.bookmarks.getTree(function(tree) {
// do some work to find a given folder in bookmarks.
// now I want to save that folder's id for access in other methods.

// Fail: 'this' refers to chrome.bookmarks.getTree.
this.root_id = computed_thing; // doesn't work!
});
}
// ... etc ...
};

我的问题是:

如何从各种 Chrome API 方法回调中访问封闭对象文字的成员?

我查看了使用模块模式,但它似乎并没有改变什么,而且这段代码不会被扩展之外的任何东西使用。

最佳答案

您需要存储对指向 contextStore 对象的 this 的引用;

var contextStore = {
'root_id': undefined,
'setup': function() {
var that = this; // Store reference here.

chrome.bookmarks.getTree(function(tree) {
that.root_id = computed_thing; // does work!
});
}
// ... etc ...
};

这相当于做;

var contextStore = {
'root_id': undefined,
'setup': function() {
chrome.bookmarks.getTree(function(tree) {
contextStore.root_id = computed_thing; // does work!
});
}
// ... etc ...
};

但是,您可以获得不在所有地方重用 contextStore 的好处。

关于javascript - 从回调内部访问对象字面量属性(异步方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8048255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com