How I Can use a variable outside the function where it was declared?
$(function() {
function init() {
var bwr_w = $(window).width();
}
init();
$('#button').click(function() {
alert('The Browser Height is' + bwr_w);
});
});
If I click on the button I get this error:
bwr_w is not defined
Variables declared outside of any function become global variables. Global variables can be accessed and modified from any function. In the above example, the variable userName becomes a global variable because it is declared outside of any function.
you have to declare the variable outside the function to use it. variables declared inside a function can only be accessed inside that function. think of each function as a box and the lid can only be opened from inside: the function can grab what's outside or put something out, but you can't reach in its box.
Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.
The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller. You have more detailed explanation here.
Just declare that variable in constructor's scope:
$(function() {
var bwr_w = null;
function init() {
bwr_w = $(window).width();
}
init();
$('#button').click(function() {
alert('The Browser Height is' + bwr_w);
});
});
try this
$(function() {
var bwr_w = 0;
function init() {
bwr_w = $(window).width();
}
init();
$('#button').click(function() {
alert('The Browser Height is' + bwr_w);
});
});
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