Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/Javascript: Defining a global variable within a function?

I have this code:

        var one;
        $("#ma1").click(function() {
            var one = 1;
        })
        $("body").click(function() {
            $('#status').html("This is 'one': "+one);
        })

and when I click the body, it says: This is 'one': undefined. How can I define a global variable to be used in another function?

like image 968
SnarkyDTheman Avatar asked Apr 30 '12 20:04

SnarkyDTheman


People also ask

Can we declare global variable inside a function in JavaScript?

Example 2: Declare the Global variable within a function using a window object. Variable declared using window objects are global variables and can be accessed from any portion of the program.

Can you define a global variable in a function?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

Can variables defined inside functions have global scope?

A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.


2 Answers

Remove the var from inside the function.

    $("#ma1").click(function() {
        one = 1;
    })
like image 163
Rocket Hazmat Avatar answered Oct 11 '22 23:10

Rocket Hazmat


If you want to make a global variable bind it to window object

window.one = 1;
like image 28
keune Avatar answered Oct 11 '22 23:10

keune