简体   繁体   中英

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()'

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:

  1. Declare imageUrl as a global variable
  2. Declare id as a global variable and run a function OnClick()
  3. Log imageUrl to the console inside the function (it displays fine)
  4. Log imageUrl to the console after the function runs (it is undefined)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM