Console access to Javascript variables local to the $(document).ready function

后端 未结 8 1257
盖世英雄少女心
盖世英雄少女心 2021-01-03 23:27

How can I access some variables inside

$(document).ready(function(){
    var foo=0;
    var bar = 3;
});

from Google chrome console? If I

8条回答
  •  情书的邮戳
    2021-01-03 23:42

    If you really need to access these variables from different parts of your code (initialize them on document ready, then accessing them elsewhere, for example), then you have to declare them outside the function closure.

    If and only if this is the case, I'm not a fan of cluttering the global space. I would suggest you to use a base object for that :

    var myObj = {};
    
    $(function() {
       myObj.foo = 0;
       myObj.bar = 3;
    });
    

    Note that they will only be set once the document is loaded! Therefore alert(myObj.foo); (or something similar) place immediately after the $(function() { ... }); block will yield undefined!

    If you only need to access them inside that context, then do not declare anything outside the function. And try to debug your code with other methods. With chrome, console.log is quite helpful, for instance.

提交回复
热议问题