我将变量newUser
从options.html
发送到background.html
,chrome.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);
答案 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