简体   繁体   English

如何使用jQuery从外部函数访问内部函数的变量?

[英]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 . 我已经看到了从内部到外部的访问函数,但是我找不到如何使用JQUERY而不是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 : AFAIK,您不能这样做,一种选择是将上下文包装在一个对象中:

$(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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