[ACCEPTED]-jquery - use a variable outside the function-definition

Accepted answer
Score: 18

Just declare that variable in constructor's 1 scope:

$(function() {
    var bwr_w = null;

    function init() {
        bwr_w = $(window).width();
    }

    init();

    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});
Score: 5

try this

$(function() {
  var bwr_w = 0;
  function init() {
    bwr_w = $(window).width();
  }
  init();
  $('#button').click(function() {
    alert('The Browser Height is' + bwr_w);
  });
});

0

Score: 1

If you declare the variable outside the 5 function, then assign a value to it inside the 4 function, it should be accessible elsewhere. So 3 long as you're sure that a value will be 2 assigned. If you're not sure, you might 1 want to assign a default value:

$(function() {

        var bwr_w; // or 'var bwr_w = default_value;'

    function init() {
        bwr_w = $(window).width();
    }
    init();
    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});
Score: 0

Try this

  $(function() {
    var bwr_w_var = function() {
        let bwr_w = 'stack overflow';
        return bwr_w;
    };
    function() {
        let bwr_w = bwr_w_var();
        console.log(bwr_w);
    };
  });

0

More Related questions