如何在函数global中定义变量newUser?

时间:2011-10-26 14:28:58

标签: javascript scope google-chrome-extension

我将变量newUseroptions.html发送到background.htmlchrome.extension.getBackgroundPage()就像这样

document.getElementById("save").addEventListener(
    "click", function ()
    {
        var newUser = document.getElementById("getEmail").value;
        var bkg = chrome.extension.getBackgroundPage();
        bkg.saveNewUser(newUser);
        console.log("newUser " + newUser);
    } , false)

background.html我有

function saveNewUser (newUser)
{
    newUser = newUser; //this should be global?
    console.log("newUser from options page " + newUser);
}

console.log("newUser from options page " + newUser);

newUser是函数的本地。我的理解是,如果变量保存在没有关键字var的函数内,它应该是全局的。但在这种情况下,它不是。函数外部的console.log会引发Uncaught ReferenceError: newUser is not defined错误。

我做错了什么?如何修改范围以在函数外部使用newUser

感谢。

修改

我在background.html中尝试了以下内容,但我仍然遇到newUser undefined错误:

var extension_user

function saveNewUser (newUser)
{
    extension_user = newUser; //this should be global
    console.log("extension_user from options page " + extension_user);
}

console.log("extension_user from options page " + extension_user);

更新

我更改了两个页面以反映答案和注释,但仍然在函数外部,变量未定义。我做错了什么?

options.html

document.getElementById("save").addEventListener(
    "click", function ()
    {
        var newUserEmail = document.getElementById("getEmail").value;
        var bkg = chrome.extension.getBackgroundPage();
        bkg.saveNewUser(newUserEmail);
        console.log("newUserEmail " + newUserEmail);
    } , false)

background.html

var newUser

function saveNewUser (newUserEmail)
{
    window.newUser = newUserEmail; //this should be global
    console.log("newUser from options page inside function" + newUser);
}

console.log("newUser from options page " + newUser);

2 个答案:

答案 0 :(得分:1)

如果要将其另存为全局变量,可以在函数中更改变量的名称:

function saveNewUser (newUserVar)
{
    newUser = newUserVar; //this should be global?
    console.log("newUser from options page " + newUserVar);
}

console.log("newUser from options page " + newUser);

或者您可以使用窗口范围(与全局范围相同):

function saveNewUser (newUser)
{
    window.newUser = newUser; //this should be global?
    console.log("newUser from options page " + newUser);
}

console.log("newUser from options page " + newUser);

所有全局变量本质上都是窗口对象的属性。

答案 1 :(得分:0)

在调用函数newUser之前,saveNewUser变量在全局范围内不存在。因此它给出了参考错误。只需将全局范围中的变量newUser声明为var newUser;即可。那应该可以解决问题。在声明变量时始终使用var关键字。这是一个很好的编程实践。永远不要在本地范围内声明全局变量。你已经知道为什么了。如果这个答案对你有帮助,请投票给我。

<强>编辑:

以下是澄清我答案的代码:

var newUser; // new user declared as a global

function saveNewUser (newuser)
{
    newUser = newuser; // this should be global?
    console.log("newUser from options page " + newUser);
}

console.log("newUser from options page " + newUser); // no more reference error