$(document).ready(function(){...})中的自调用函数; [英] Self calling functions inside of $(document).ready(function(){ ... });

查看:90
本文介绍了$(document).ready(function(){...})中的自调用函数;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将我的javascript封装在

I've already encapsulated my javascript in

jQuery(document).ready(function($) {

});

我想知道通过这两种方式调用函数内部的含义是什么:

I was wondering what the implications were of calling functions inside of it via these two ways:

jQuery(document).ready(function($) {
    $(function () {
        // do something
    });
});

vs

jQuery(document).ready(function($) {
    (function () {
        // do something
    })();
});

编辑:

我也想知道这两者中哪一个更正确的做事方式?随意添加您自己的实现。

I also wanted to know which of the two would be the more "correct" manner of doing things? Feel free to add your own implementation.

推荐答案

不同之处在于执行顺序:

In difference lies in the order of execution:

jQuery(document).ready(function($) {
    $(function () {
        // inner handler
    });
    // outer handler
});

执行内部 ready 处理程序内的代码在外部处理程序中的代码之后: http://jsfiddle.net/nmD8b/

Code inside the inner ready handler is executed after the code in the outer handler: http://jsfiddle.net/nmD8b/.

jQuery(document).ready(function($) {
    (function () {
        // do something
    })();
    // outer handler
});

立即函数表达式内的代码在定义函数的位置执行,即在代码跟在表达式之前: http://jsfiddle.net/nmD8b/

Code inside the immediate function expression is executed right where the function is defined, i.e. before code following the expression: http://jsfiddle.net/nmD8b/.

如果要范围变量,请使用第二种方式。第一种方式没有多大意义,您只应在实际需要时注册 ready 事件处理程序。在这种情况下,DOM已经准备就绪,因为您将处理程序绑定在另一个就绪处理程序中。

If you want to scope variables, use the second way. The first way does not make a lot of sense, you should only register ready event handlers when you actually need them. In this case, the DOM is already ready, because you bind the handler inside another ready handler.

如果您不想对变量进行范围调整,请不要使用它们。只需将所有代码放在外部处理程序中。

If you don't want to scope variables, use neither of them. Just put all your code inside the outer handler.

这篇关于$(document).ready(function(){...})中的自调用函数;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆