JQuery IIFE 外部文档就绪 - 模式错误

JQuery IIFE outside document ready - bad pattern

本文关键字:模式 错误 就绪 文档 IIFE 外部 JQuery      更新时间:2023-09-26

嘿伙计们 我已经有一段时间来处理这种"模式"了,但我无法欣赏这种架构选择。在我看来,这很糟糕且毫无意义的代码。

我附上一个代码示例以更说明。

所有这些在文件之外宣布的IIFE都准备好了不好的做法吗?这是一种模式还是只是意大利面条JS?有什么弱点或架构错误吗?

索引.html

<html>
    <head>
        <meta HTTP-EQUIV='content-type' CONTENT='text/html; charset=utf-8'/>
    </head>
    <body>
        <div id="first"></div>
        <div id="second" style="border:2px solid green;width:150px;height:190px;"></div>
    </body>
    <script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>
    <script type='text/javascript' src='js/scope.js'></script>

</html>

范围.js

(function() {
    if (typeof $M === 'undefined') { $M = {}; }

    var 
        $document = $(document);
        $first = $('#first'),
        $second = $('#second'),
        $chunk = $("<div id='chunk'> truffle shuffle </div>"),
        documentHeight = $document.height(),
        animationTime = 1000,
        style = {
            'border':'2px solid red',
            'height': documentHeight / 8,
            'width': '150px'
        },
        style2 = {
            'height': documentHeight / 4,
            'width': '300px'
        };

    var init = function() {
        $second.hide(); // init ops
    }
    function appendChunk() {
        $first.append($chunk);
        $chunk.css(style);
    }
    function animateChunk() {
        $chunk.animate(style2,animationTime,function(){
            $(this).trigger('animationComplete');
        });
    }
    appendChunk();
    animateChunk();
    $M.one = init;
})();

(function() {
    if (typeof $M === 'undefined') { $M = {}; }
    var 
        $second = $('#second'),
        $chunk = $("#chunk"),
        animationTime = 1000,
        style = {
            'border':'2px solid red',
            'height': '150px',
            'width': '150px'
        };
    var init = function() {
        $second.hide(); // init ops
    }
    $chunk.on('animationComplete',function(){
        $second.fadeIn().trigger('animationComplete');
    });
    $second.on('animationComplete',function(){
        $chunk.animate(style,animationTime);
    });
    var time = setInterval(function() {
            if($second.is(':visible')) {
                console.log("visible");
                clearInterval(time);
            } else {
                $second.html("finished!");
            }
    },200);
    $M.two = init;
})();

$(document).ready(function () {
    $M.one();
    $M.two();
});

注意:在撰写本文时,您的问题中没有代码。 它现在就在那里,见下文。

所有这些在文件之外宣布的IIFE都准备好了不好的做法吗?

完全没有,它们对确定范围很有用。

我通常不使用jQuery的ready,因为我更喜欢将script元素放在页面底部,所以我使用IIFE来避免任何全局变量并noConflict兼容:

(function($) {
    // My code here
}(jQuery);

(现在问题中有代码...

但是,如果您担心不良做法,则应标记以下内容:

if (typeof $M === 'undefined') { $M = {}; }

这依赖于隐式全局的恐怖,并且与ES5的"严格"模式不兼容。

下面是可用于这种情况的模式:

// By default, global scope is not strict
(function(global) {
    // Now we turn on strict
    "use strict";
    if (typeof global.$M === 'undefined') { global.$M = {}; }
    var $M = global.$M;
    // ...
})(this);

或者在浏览器上,只需使用 window

(function() {
    // Now we turn on strict
    "use strict";
    if (typeof window.$M === 'undefined') { window.$M = {}; }
    var $M = window.$M;
    // ...
})();

大多数人(或至少是我!)出于以下原因使用IIFE:

将变量包装在函数中,这样它们就不会全局化

这非常有用。你会用其他文件的无用变量污染你的浏览器环境 - 所以你把所有代码包装在一个IIFE中,它们不会全局化,同时函数范围内的所有代码都可以访问。基本上,这是一种在JS中获取"私有变量"的方法。

通过削减一些全局变量来减小缩小大小

例如,当您执行以下操作时:

(function( window, document, undefined ) {
  // ...
})( window, document );

考虑到您确实在该范围内大量使用这 3 个变量,您的最终缩小文件将小得多

(function( a, b, c ) {
  // code with all references to window, document and undefined renamed
})( window, document );

我希望这可以帮助您理解为什么使用 IIFE。
此外,阅读本·阿尔曼对他们的评价总是好的。他是Grunt的创造者.js :)