Skip to content Skip to sidebar Skip to footer

How Can I Make The Variable Newuser Defined Inside A Function Global?

I send the variable newUser from options.html to background.html with chrome.extension.getBackgroundPage() like this document.getElementById('save').addEventListener( 'click',

Solution 1:

If you want to save it as a global variable, you can either change the name of the variable in the function:

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

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

or you can use the window scope (which is the same as the global scope):

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

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

All global variables are essentially properties of the window object.

Solution 2:

The newUser variable does not exist in the global scope until the function saveNewUser is called. Thus it gives a reference error. Just declare the variable newUser in the global scope as var newUser;. That should solve the problem. Always use the var keyword when declaring variables. It's a good programming practice. Never declare global variables within local scopes. You already know why. Please vote for me if this answer helped you.

Edits:

Here's the code to clarify my answer:

var newUser; // new user declared as a globalfunctionsaveNewUser (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

Post a Comment for "How Can I Make The Variable Newuser Defined Inside A Function Global?"