I'm trying to understand why my global variable 'imageUrl' behaves differently inside and outside of the function 'genericOnClick()'
var imageUrl
var id = chrome.contextMenus.create({
"title": "Add to JC Queue",
"contexts": ["image"],
"onclick": genericOnClick
});
function genericOnClick(info) {
imageUrl = info.srcUrl;
console.log(imageUrl);
chrome.tabs.create({
url: chrome.extension.getURL('dialog.html'),
active: false
}, function (tab) {
// After the tab has been created, open a window to inject the tab
chrome.windows.create({
tabId: tab.id,
type: 'popup',
focused: true
});
});
}
console.log(imageUrl);
Please let me know where I am going wrong:
When the second console.log
is run, the function has not been called, therefore the variable hasn't been assigned anything yet. However, inside the function it has received a value, and that's what you see.
好吧,当您在调用函数之前记录日志时, imageURL
是 undefined
,代码末尾的日志在调用函数之前运行。
The last line ( console.log(imageUrl);
) runs almost immediately after you declare imageUrl
without a value, so it is undefined at that point.
Try setting imageUrl
to an initial value, and you'll see that that value will get logged.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.