立即调用函数表达式和文档就绪函数

问题描述 投票:1回答:1

在使用jQuery的Javascript中,我可以使用Immediately Invoked Function Expression为函数添加范围并传递函数jQuery,并命名参数$

(function ( $ ) { 

    $.fn.greenify = function() {
        this.css( "color", "green" );
        return this;
    }; 

}( jQuery ));

同样,我们编写文档就绪函数如下

$(function() {
    console.log( "ready!" );
    // use $ variable here
});

这是否意味着文档就绪功能已经作用域? 我是否还需要传递函数jQuery,并在文件就绪函数中命名参数$?类似下面的东西

$(function ( $ ) {
    console.log( "ready!" ); 
    // use $ variable here   
 }( jQuery ));
javascript jquery
1个回答
0
投票

IIFE立即被调用,它不会等待document做好准备。所以:

(function($) {

    // here document is not necessarly ready

})(jQuery);

当你做$(function() { ... });你没有创建一个IIFE时,你只是传递一个函数(回调),当document准备就绪时执行。

如果您想同时执行这两项操作,请使用:

(function($) {

    $(function() {

        // here, document is really ready
        // $ available here too

    });

})(jQuery);

或者这样做(使用jQuery passes itself as parameter to its ready callback的事实):

jQuery(function($) {

    // here, document is really ready
    // and $ is obviously available (only here)

});
© www.soinside.com 2019 - 2024. All rights reserved.