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?
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.
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.
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.
Remove the var
from inside the function.
$("#ma1").click(function() {
one = 1;
})
If you want to make a global variable bind it to window
object
window.one = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With