首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么在函数中没有var保存这个变量,而不是全局的?

为什么在函数中没有var保存这个变量,而不是全局的?
EN

Stack Overflow用户
提问于 2011-10-27 15:17:14
回答 3查看 300关注 0票数 1

这个问题与I asked yesterday类似的javascript范围问题有关。我希望你能帮我解决这个问题。

我正在使用Chrome扩展程序。options.html将新的用户电子邮件保存为“用户”,并在background.html中调用refreshUser()函数。

代码语言:javascript
运行
复制
//save entered gmail address
document.getElementById("save").addEventListener(
    "click", function ()
    {
        var user = document.getElementById("getEmail").value;
        localStorage.setItem("user", user);
        chrome.extension.getBackgroundPage().refreshUser();
    } , false)

然后,我将电子邮件保存为"newUser“在background.html中。问题是newUser是在refreshUser()内部更新的,但它是refreshUser()之外的null

代码语言:javascript
运行
复制
newUser = localStorage.getItem("user");
console.log("first newUser " + newUser);
//newUser=null

function refreshUser () 
{
    newUser = localStorage.getItem("user");
    console.log("newUser inside of refreshUser function " + newUser);
    //newUser is updated with saved email in localStorage
}

console.log("newUser after refreshUser() " + newUser);
//newUser=null

为什么在没有newUser关键字的情况下定义refreshUser()是本地的?谢谢你的帮忙!

更新

为了响应pimvdb's answer,我复制了background.html的代码。如果我想按指示在newUser中使用formData,需要在refreshUser()中调用哪个函数?谢谢。

代码语言:javascript
运行
复制
<html>
<script>

newUser = localStorage.getItem("user");
console.log("first newUser " + newUser);

function refreshUser () 
{
    newUser = localStorage.getItem("user");
    console.log("newUser inside of refreshUser function " + newUser);
}

console.log("newUser after refreshUser() " + newUser);

//I want to user newUser below in formData  
chrome.browserAction.onClicked.addListener(function(tab) 
{
    chrome.tabs.getSelected(null, 
    function(tab) 
    {
        // Send a request to the content script.
        chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, 
        function(response) 
        {
            var firstParagraph = response.dom;

            var formData = new FormData();
            formData.append("url", tab.url);
            formData.append("title", tab.title);
            formData.append("pitch", firstParagraph);
            formData.append("extension_user", "abc@gmail.com");
            //I want to user newUser here:
            //formData.append("extension_user", newUser);
            console.log("newUser inside formData: " + newUser)

            var xhr = new XMLHttpRequest();
            xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
            xhr.onreadystatechange = 
            function (aEvt) 
            {
                if (xhr.readyState == 4) 
                {
                    if (xhr.status == 200)
                    { 
                        console.log("request 200-OK");
                        chrome.browserAction.setBadgeText ( { text: "done" } );
                        setTimeout(function () 
                        {
                            chrome.browserAction.setBadgeText( { text: "" } );
                        }, 2000);
                    }
                    else
                    {
                        console.log("connection error");
                        chrome.browserAction.setBadgeText ( { text: "ERR" } );
                    }        
                }        
            };
            xhr.send(formData);
        }); //chrome.tabs.sendRequest
    });
});


</script>
</html>

响应的更新

我遇到的问题是,当浏览器打开时,background.html被加载,但是电子邮件随后保存在options.html中。所以refreshUser()告诉background.html从localStorage获取newUser。然后我需要在formData中使用“formData”,如下所示:

代码语言:javascript
运行
复制
formData.append("extension_user", newUser);

但是,我现在在refreshUser()之外使用“refreshUser()”的方式是空的。我遗漏了什么?

更新以澄清为什么某些日志没有显示在控制台中

我就是这样做的:

代码语言:javascript
运行
复制
1. I reload the extension and start with localStorage empty
2. I use the extension to save a bookmark
3. all 3 logs are null as expected

 first newUser null
 newUser after refreshUser() null
 newUser inside formData: null
 request 200-ok

4. now I save user email in options as abc@gmail.com
5. now I use the extension again to save a bookmark
6. now refreshUser is executed and the log inside the function says abc@gmail.com and formData log says abc@gmail.com

newUser inside of refreshUser function abc@gmail.com
newUser inside formData: abc@gmail.com
request 200-OK

7. but what confuses me is that now the first 2 logs do not show in the console. Why?
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-10-27 15:22:52

它是全球性的,但你在错误的时间访问它。

function refreshUser () { ... }只是一个函数声明;什么都没有真正执行。这两个声明之外的日志都会立即运行,此时尚未设置localStorage项(即是null)。

您的措辞"newUser after refreshUser()“相当矛盾。它确实是在声明之后执行的,但是newUser根本没有被更改,所以这两个日志都在函数日志null之外。您无法访问它时,它还没有设置,但你似乎期待。

由于全局变量已被更新,下面的日志应该是正确的。只需在refreshUser中设置它之后调用它。

代码语言:javascript
运行
复制
function otherFunction() {
    // logs the global variable 'newUser', which is thus indeed global
    console.log("newUser inside otherFunction: " + newUser);
}

function refreshUser () 
{
    newUser = localStorage.getItem("user");
    otherFunction();
}
票数 2
EN

Stack Overflow用户

发布于 2011-10-27 15:23:21

您还没有在发布的代码段中调用refreshUser(),所以不会设置它。

尝试调用它,然后检查全局newUser。

票数 2
EN

Stack Overflow用户

发布于 2011-10-27 15:37:15

我只想评论一下定义变量的做法,但这太长了,不能发表评论。

您永远不想定义没有var关键字的新变量,它会导致各种各样的欺骗和意外结果。如果要确保它是全局变量,请使用全局对象。

代码语言:javascript
运行
复制
var globalObject = this,
    globalVariable = 1; //or globalObject.globalVariable = 1;

function example(){
var globalVariable;

globalVariable = 2 //This will not set the global variable and you can see it's not intended either since we used var
console.log( globalObject.globalVariable ); 
globalObject.globalVariable = 2 // This will set the global variable, the intent to do so is very explicitly shown
console.log( globalObject.globalVariable ); 
}

example();
//1
//2
console.log( globalObject.globalVariable, globalVariable );
//2 2
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7918179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档