javascript - (function(){})() 的问题

标签 javascript jquery jquery-ui

<分区>

到目前为止,我已经了解了使用此功能的好处(它是包装吗?)

因此,它几乎就像命名空间一样。 假设我们有:

( function() {

    function foo(){
        alert(true);
    }

    foo(); //alerts true

})();


( function() {

    function foo(){ //the same title of the function as above
        alert("another call of foo");
    }

    foo(); //alerts, ok.

})();

我还注意到它可以访问公共(public)变量,如下所示:

var __foo__ = 'bar';

( function() {

    alert(__foo__); //alerts bar

})();

我有几个关于这种方法的问题

我尝试过的:

  1. 使用 Bing 获取教程(我找到了它们,但其中很多都没有回答我的问题)
  2. 玩将物体传递到体内
  3. 在这里找到答案

但是,我还在用头撞墙

所以问题是:

我见过人们将对象作为参数传递,但什么时候才有意义? 例如,它是什么意思?

  1. ( function(window) {
    
    
    })(document);
    
  2. 我在 Jquery UI Lib 中看到了这样的东西

    ( function($) {
        //some code of widget goes here
    })(Jquery);
    

这使得内部代码在函数外可见,对吧? (不确定)为什么,这是因为 我们可以访问对象(假设我们有“模态”小部件),只需调用它,

喜欢:

$(function(){

    $("#some_div").modal(); //here it's object the we got from the function
});

第二个问题是:它是如何工作的。

最佳答案

I've seen people pass objects as params, but when DOES it make sense? For example, what does it mean?

( function(window) {
 })(document);

该语言不会将直接调用函数的参数与其他函数的参数区别对待。

只要您希望在函数体中使用局部名称作为输入,就可以使用参数。在这种情况下,它有点令人困惑,因为 windowdocument 很可能会混淆。


( function($) {
     //some code of widget goes here
})(Jquery);

This makes inner code visible outside the function, right? (not sure) Why, this is because we can access the object (say we have "modal" widget), simply by calling it,

没有。它本身不会使任何代码在小部件外部可见。它只是一个参数定义,它为全局变量提供了一个新的本地名称。

使内部代码在外部可见的原因是将其附加到外部对象,如

$.exportedProperty = localVariable;

这是 jQuery 代码中的常见约定。

关于javascript - (function(){})() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11975422/

相关文章:

Javascript:类似java的包和类冲突问题

javascript - 本地存储适配器简介

JavaScript touchend 与 click 困境

jquery - 使用 jQuery 重新排序 div 位置?

javascript - 如何在失败的ajax post请求上恢复可拖动元素

javascript - Jquery,可拖动的div不会使用Firefox在内部自动调整 Accordion 的大小

javascript - 当父级/主体进行缩放变换时获取元素上的触摸位置

javascript - 如何检查浏览器窗口是否处于事件状态?

jquery - Datepicker获取maxDate或Mindate

javascript - 可手动操作。获取所有验证错误的列表