Home > Web Front-end > JS Tutorial > body text

How does jQuery call its self-calling anonymous function?

不言
Release: 2018-08-01 16:04:16
Original
3830 people have browsed it

This article introduces to you how jQuery calls self-calling anonymous functions? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Open the jQuery source code, first you will see this code structure:

(function(window,undefined ){
})();
Copy after login

This is a self-calling anonymous function. What stuff? In the first bracket, create an anonymous function; in the second bracket, execute it immediately

Why create such a "self-calling anonymous function"?
By defining an anonymous function, a "private" namespace is created. The variables and methods of this namespace will not destroy the global namespace. This is very useful and a feature that a JS framework must support. jQuery is used in thousands of JavaScript programs. It must be ensured that the variables created by jQuery cannot conflict with the variables used by the program that imports it.
Next, let’s take a look at what functions are implemented in self-calling anonymous functions, arranged in code order:

(function( window, undefined ) {
// 构造jQuery对象
var jQuery = function( selector, context ) {
    return new jQuery.fn.init( selector, context, rootjQuery );
}
// 工具函数 Utilities
// 异步队列 Deferred
// 浏览器测试 Support
// 数据缓存 Data
// 队列 queue
// 属性操作 Attribute
// 事件处理 Event
// 选择器 Sizzle
// DOM遍历
// DOM操作
// CSS操作
// 异步请求 Ajax
// 动画 FX
// 坐标和大小
window.jQuery = window.$ = jQuery;
})(window);
Copy after login

Anonymous functions are called function literals grammatically. JavaScript syntax requires parentheses surrounding anonymous functions. In fact, there are two ways to write self-calling anonymous functions:

(function() {
console.info( this );
console.info( arguments );
}( window ) );
Copy after login
(function() {
console.info( this );
console.info( arguments );
})( window );
Copy after login

Why do we need to pass in window?

By passing in the window variable, the window changes from a global variable to a local variable. When accessing the window in a jQuery code block, there is no need to roll back the scope chain to the top-level scope, which can be faster. Access the window; this is not the key. More importantly, passing the window as a parameter can be optimized when compressing the code. Take a look at jquery-1.6.1.min.js: (function(a,b){} )(window); // window is optimized to be a
Through the above introduction, we roughly understand that () can make a function expression execute immediately.

As a "container", the anonymous function can access external variables inside the "container", but the external environment cannot access the variables inside the "container",
So ( function(){...} )() Internally defined variables will not conflict with external variables, commonly known as "anonymous wrappers" or "namespaces".

(function () {
// ... 所有的变量和function都在这里声明,并且作用域也只能在这个匿名闭包里
// ...但是这里的代码依然可以访问外部全局的对象
}());
Copy after login

Same as below
(function () {/ Internal code/})();

In layman’s terms, () is used to evaluate , so this () cannot be empty at any time because it needs to be calculated. Function parsing will only parse to {}, not ().

Putting the expression in () will return the value of the expression;
Putting the function in () will return the function itself; (function(){}());
If () immediately following the function means that the function is called, that is, the function is evaluated: (function(){})();

(function() {
//自执行函数中的内部变量,外部是无法访问的
var name = 'kevin';
})( window );
Copy after login

name //undefined, the value of name cannot be obtained

During the running process of the code, [already declared functions] will be parsed first;

          and the function expression will not be parsed until it is executed;
                                                                                                                                                                                                                         
, so its execution requires the call of other functions. The anonymous functions usually seen are passed as parameters. The immediate execution function itself is an anonymous function,
          The order of js code execution:
            //The function test(){}
that has been declared                                                                                                     to                                             to be executed immediately                                        //Function expression var test = function(){}
                                                                                  //                                         //                                                                                                                                                          , there are a few points to understand:

1. If you want to add parentheses after the function body to call it immediately, the function must be a function expression, not a function declaration;

2. Execute the function immediately It can be regarded as a private scope. External variables can be accessed inside the scope, but the external environment cannot access variables inside the scope. Therefore, the immediate execution function is a closed scope and will not interact with the external scope. conflict.

JQuery uses this method. Wrap the JQuery code in (function (window, undefined){...jquery code...} (window). When calling the JQuery code in the global scope, you can protect JQuery internal variables. The role of.
3. Module mode is an advanced mode of self-executing functions. It is very convenient to call closure functions with global objects in each anonymous closure.
a. Create an anonymous function expression that is called immediately
b. Return a variable, which contains what you want to expose
c. The returned variable will be assigned to window

(function () {
var i = 0;
return {
    get: function () {
        return i;
    },
    set: function (val) {
        i = val;
    },
    increment: function () {
        return ++i;
    }
};
} (window));
Copy after login
    // window作为一个带有多个属性的全局对象,上面的代码对于属性的体现其实是方法,它可以这样调用:
    window.get(); // 0
    window.set(3);
    window.increment(); // 4
    window.increment(); // 5

    window.i; // undefined 因为i不是返回对象的属性
    i; // 引用错误: i 没有定义(因为i只存在于闭包)
Copy after login

/


The above is the analysis of self-calling anonymous functions, so how is such a function called?

*//The following is about the call of global variables, that is, the call of anonymous closure function
*/Move out of Module mode againModule mode, that is, the creation and invocation of anonymous closures:

   a.创建一个立即调用的匿名函数表达式
   b.return一个变量,其中这个变量里包含你要暴露的东西
      c.返回的这个变量将赋值给window
Copy after login

window(或者是任意一个全局对象)作为一个带有多个属性的全局对象,也可以把window当成一个参数,以对象的方式,在其它函数中实现调用。用下面的例子说明:

(function ($, YAHOO) {
// 这里,我们的代码就可以使用全局的jQuery对象了,YAHOO也是一样
$.aa = function(){
    //code
}
} (jQuery, YAHOO));
//调用 jQuery.aa();
Copy after login

下面是一个标准的Module模式,通过匿名函数的返回值来返回这个全局变量:

var blogModule = (function () {
var my = {}, privateName = "博客园";

function privateAddTopic(data) {
    // 这里是内部处理代码
}

my.Name = privateName;
my.AddTopic = function (data) {
    privateAddTopic(data);
};

return my;
} ());
//调用 blogModule.my();
Copy after login

在一些大型项目里,将一个功能分离成多个文件是非常重要的,因为可以多人合作易于开发。再回头看看上面的全局参数导入例子,我们能否把blogModule自身传进去呢?答案是肯定的,我们先将blogModule传进去,添加一个函数属性,然后再返回就达到了我们所说的目的:

var blogModule = (function (my) {
my.AddPhoto = function () {
    //添加内部代码  
};
return my;
} (blogModule || {}));
Copy after login


(function (my){
my.AddPhoto = function () {
    //添加内部代码  
};
return my;
})(blogModule || {}));
//调用 blogModule.AddPhoto();
Copy after login

那么,多个自执行函数间是怎么调用的呢?

(function(owner) {
//第一个匿名闭包
owner.debug = true;
//Ajax相关参数配置
owner.ajax = {
    timeout: 10000,
    type: 'post',
    dataType: 'json',
};
})(window.C = {}));
Copy after login

如果第二个函数想调用 全局变量为C中的 对象呢?要怎么写?

(function($, owner) {
//这里调用上面全局变量为C 中的对象呢
if(!C.debug) return false;
var url = 'aaa.html';
mui.ajax({
    url: url,
    dataType: C.ajax.dataType,
    type: C.ajax.type,
});
})(mui, window.app = {});
Copy after login

再举个例子,同样的,不同自执行闭包函数间的调用方法:

(function($, owner) {
//获取语言闭包
owner.getLanguage = function() {
    var language = localStorage.getItem(C.state.field.language);
    if(typeof language == "undefined" || language === null || language == '') {
        var currentLang = navigator.language;
        if(!currentLang)
            currentLang = navigator.browserLanguage;
        language = currentLang.toLowerCase();
        language = language.replace(/-/g, '_');

        if(language != 'en_us' && language != 'zh_cn')
            language = 'en_us';

        localStorage.setItem(C.state.field.language, language);
    }

    //在上面的解析中有说过,Module模式,return 一个变量,这个变量就是要爆露的东西。通过这个函数的全局变量,这个  language  可以在任何地方调用   
    //return一个变量,其中这个变量里包含你要暴露的东西 
    //全局调用  storage.language                                  
    return language;
};
})(mui, window.storage = {}));
Copy after login
(function($, owner) {
owner.language = {};
owner.preload = function(settings){
    var defaults = {
        name: 'i18n',
        language: '',
        path: '/',
        cache: true,
        encoding: 'UTF-8',
        autoReplace: true,
        success: null,
        error: null,
    };
    
    settings = $.extend(defaults, settings);
    if(settings.language === null || settings.language == '') {
        //全局调用  storage.language                                                                            
        settings.language = storage.getLanguage();
    }
}   
})(mui, window.i18n = {});
Copy after login

所以 匿名闭包的调用规则是这样的,立即执行(最后一个括号) (window),如果把window作为一个参数进行传递,那么就把它以对象的方式,在其它函数中实现全局调用。

相关推荐:

js实现模态窗口增加与删除案例分享(纯代码)

js对象类型怎么判断?详解js里的基本类型转换

The above is the detailed content of How does jQuery call its self-calling anonymous function?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!