jquery/JavaScript quickie,那些括号里有什么

jquery/javascript quickie, what are those parenthesis holding?

本文关键字:什么 那些 JavaScript quickie jquery      更新时间:2023-09-26

我遇到了一些javascript或jQuery函数,它们在方法的末尾有一个封闭的值或对象。 例:

(function ($) {
        var delay = 0;
        $.fn.translate3d = function (translations, speed, easing, complete) {
            var opt = $.speed(speed, easing, complete);
            opt.easing = opt.easing || 'ease';
            translations = $.extend({ x: 0, y: 0, z: 0 }, translations);
            return this.each(function () {
                var $this = $(this);
                $this.css({
                    transitionDuration: opt.duration + 'ms',
                    transitionTimingFunction: opt.easing,
                    transform: 'translate3d(' + translations.x + 'px, ' + translations.y + 'px, ' + translations.z + 'px)'
                });
                setTimeout(function () {
                    $this.css({
                        transitionDuration: '0s',
                        transitionTimingFunction: 'ease'
                    });
                    opt.complete();
                }, opt.duration + (delay || 0));
            });
        };
    })(jQuery);

<script type="text/javascript">
    (function (d, t) {
<snip>
    })(document, 'script');
</script>

函数末尾那些用括号括起来的项目的目的是什么?我在SO上找到了几个答案,但没有一个可以清除它。 谢谢

它使用参数定义一个匿名函数,将值分配给函数的参数,然后调用它。

此方法的优点是,您不会用函数和变量污染命名空间,而这些函数和变量不会在函数内以外的其他任何地方使用。

更详细地说,

(function() {} ...声明匿名函数,并在末尾添加()调用刚刚创建的函数。

它形成一个自调用匿名函数。优点是所有标识符的范围都限定在该函数内,而不是具有全局范围。

这是一个很好的链接,可以了解更多细节:http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

下面是一个示例:

(function() {
  var foo = "bar";
  console.log(foo); // prints bar
})();
console.log(foo);  // prints undefined since foo is scoped within the function

当像这样重写时,可能更容易理解上面的代码片段:

function fun() {
  var foo = "bar";
  console.log(foo);
}
fun();

这两个代码片段实现相同的目标。唯一的区别是,在第一个代码段中,您没有命名函数然后调用它。而是将其创建为匿名函数,并立即调用它。

当您想要将对象绑定到某个变量时,这也很有用,例如在代码片段中使用jQuery完成:

var $ = {}; // define $ to an empty object instead of the jQuery object
(function($) {
  // within this function, $ will always be the jQuery object
  // protecting you from re-definitions outside the funciton
  console.log($);
})(jQuery);

上面的代码片段创建了一个匿名函数,该函数接受单个参数 $ ,然后立即调用传入 jQuery 对象的函数,确保在函数中$始终引用jQuery对象。

自调用匿名函数的另一个有趣的应用是,当您想要在延迟执行的情况下将变量绑定到特定对象时。

var markers = []; //an array of google map markers
for(var i = 0; i < markers.length; i++) {
  // do something with markers[i];
  // then schedule it for removal after 2 seconds
  setTimeout(function() { markers[i].setMap(null); }, 2000);
}

上述代码片段的问题在于,当标记删除代码在 2 秒后运行时,i的值届时会发生变化,因为循环会继续。这可以通过使用自调用 anon 函数创建闭包来补救:

for(var i = 0; i < markers.length; i++) {
  // do something with markers[i];
  // then schedule it for removal after 2 seconds
  (function(j) {
    setTimeout(function() { markers[j].setMap(null); }, 2000);
  })(i);
}

现在,j绑定到当前值 i ,因此当删除代码在 2 秒后运行时,它会以预期的值 i 运行,即使此后i已更改。