[英]Why does this global Javascript variable behave differently inside and outside of a function?
I'm trying to understand why my global variable 'imageUrl' behaves differently inside and outside of the function 'genericOnClick()' 我试图了解为什么我的全局变量'imageUrl'在函数'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. 当运行第二个console.log
,尚未调用该函数,因此尚未为变量分配任何东西。 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. 最后一行( console.log(imageUrl);
)在声明不带任何值的imageUrl
之后几乎立即运行,因此在这一点上它是未定义的。
Try setting imageUrl
to an initial value, and you'll see that that value will get logged. 尝试将imageUrl
设置为初始值,您会看到该值将被记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.