简体   繁体   English

jquery function 内 function

[英]jquery function inside a function

Is it possible to have a function within another function like so?是否可以像这样在另一个 function 中有一个 function?

function foo() {

    // do something

    function bar() {

        // do something

    }

    bar();

}

foo();

Yes you can have it like that.是的,你可以拥有它。 bar won't be visible to anyone outside foo . foo之外的任何人都看不到bar

And you can call bar inside foo as:您可以在foo中调用bar为:

function foo() {

    // do something

    function bar() {

        // do something

    }
    bar();

}

Yes, you can.是的你可以。
Or you can do this,或者你可以这样做,

function foo(){

    (function(){

        //do something here

    })()

}

Or this,或这个,

function foo(){

    var bar=function(){

        //do something here

    }

}

Or you want the function "bar" to be universal,或者您希望 function “bar”是通用的,

function foo(){

    window.bar=function(){

        //something here

    }

}

Hop this helps you.跳这对你有帮助。

That's called a nested function in Javascript.这称为 Javascript 中的嵌套 function。 The inner function is private to the outer function, and also forms a closure.内部 function 是外部 function 和 forms 闭包私有的。 More details are available here .更多详细信息可在此处获得。

Be particularly careful of variable name collisions, however.但是,要特别小心变量名冲突。 A variable in the outer function is visible to the inner function, but not vice versa.外部 function 中的变量对内部 function 可见,但反之则不可见。

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

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