javascript - jQuery: How to set the global variable from one function and access it to another function? -


how can declare,set , access global variable 1 function another?

var testvar;  $(document).ready(function(){  test1();  });    function test1(){    return testvar;  }    function test2(){    var = "hellow world";    testvar = a;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

the code above sample make easy understand on trying do. educational purposes. want result in way. or there way set global variable within function , use function outside function?

what to?

creating variables in global scope very bad practice. shouldn't because can cause conflicts especially in future javascript versions.

you can run functions scope or object, try:

var shared = {};  $(document).ready(function () {     test1.call(shared);//undefined     test2.call(shared);     test1.call(shared);//foo });  function test1 () {     alert(this.testvar); }  function test2 () {     var = 'foo';     this.testvar = a; } 

how works

in simple terms, store variables in object (shared). can declared "shared variable" using this. instead of var. using .call() can choose run function in scope of object. i'm not best @ explaining, learn more here

fiddle


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -