简体   繁体   中英

How to access the inner function's variable from outer function with jQuery?

I have saw access function from inside to outside, but I can not find an exact answer on how to access inner functions's variable from outer function with JQUERY, not javaScript .

I have code below

$(document).ready(function(){
    var outv=1;
    function innerfunc(){
        var innerfuncv=2;
        var outv=3;
        alert(outv);

    };
    alert(outv);
    innerfunc();
    alert(outv);
    alert(innerfunc.outv);



});//$(document).ready(function() END

Please help. Thanks! Let me know if there is more info needed.

Define them outside the function. Variables defined inside a function are only accessible for that function, so you have to define them outside the function if you want to access them.

$(document).ready(function () {
    var outv = 1;
    var innerfuncv;
    function innerfunc() {
        innerfuncv = 2;
        outv = 3;
        alert(outv);
    };
    alert(outv);
    innerfunc();
    alert(outv);
   /* alert(innerfunc.outv); this wont work*/
});

AFAIK, you can't do that, one option would be to wrap your context in an object :

$(document).ready(function(){
    var outv=1;

    var inner = {
        innerfuncv:2,
        outv:3,
        innerfunc : function (){        
                       console.log(this.outv);
                    }
        }      
    console.log(outv);
    inner.innerfunc();
    console.log(outv);
    console.log(inner.outv);
});
$(document).ready(function(){
    var outv=1;//you can access this any where within dom ready..
    function innerfunc(){
       var innerfuncv=2;//this is a local variable and its scope is within function
         outv=3;//get rid of var when you have already declared it.
        alert(outv);//this will get overWritten..1 is replaced by 3

    };
    alert(outv);//will alert 1
    innerfunc();
    alert(outv);//will alert 3,not 1



});//$(document).ready(function() END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM