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 ){ })();
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);
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 ) );
(function() { console.info( this ); console.info( arguments ); })( window );
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都在这里声明,并且作用域也只能在这个匿名闭包里 // ...但是这里的代码依然可以访问外部全局的对象 }());
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 );
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));
// window作为一个带有多个属性的全局对象,上面的代码对于属性的体现其实是方法,它可以这样调用: window.get(); // 0 window.set(3); window.increment(); // 4 window.increment(); // 5 window.i; // undefined 因为i不是返回对象的属性 i; // 引用错误: i 没有定义(因为i只存在于闭包)
/
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 window(或者是任意一个全局对象)作为一个带有多个属性的全局对象,也可以把window当成一个参数,以对象的方式,在其它函数中实现调用。用下面的例子说明: 下面是一个标准的Module模式,通过匿名函数的返回值来返回这个全局变量: 在一些大型项目里,将一个功能分离成多个文件是非常重要的,因为可以多人合作易于开发。再回头看看上面的全局参数导入例子,我们能否把blogModule自身传进去呢?答案是肯定的,我们先将blogModule传进去,添加一个函数属性,然后再返回就达到了我们所说的目的: 或 那么,多个自执行函数间是怎么调用的呢? 如果第二个函数想调用 全局变量为C中的 对象呢?要怎么写? 再举个例子,同样的,不同自执行闭包函数间的调用方法: 所以 匿名闭包的调用规则是这样的,立即执行(最后一个括号) (window),如果把window作为一个参数进行传递,那么就把它以对象的方式,在其它函数中实现全局调用。 相关推荐: 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!
*/Move out of Module mode againModule mode, that is, the creation and invocation of anonymous closures: a.创建一个立即调用的匿名函数表达式
b.return一个变量,其中这个变量里包含你要暴露的东西
c.返回的这个变量将赋值给window
(function ($, YAHOO) {
// 这里,我们的代码就可以使用全局的jQuery对象了,YAHOO也是一样
$.aa = function(){
//code
}
} (jQuery, YAHOO));
//调用 jQuery.aa();
var blogModule = (function () {
var my = {}, privateName = "博客园";
function privateAddTopic(data) {
// 这里是内部处理代码
}
my.Name = privateName;
my.AddTopic = function (data) {
privateAddTopic(data);
};
return my;
} ());
//调用 blogModule.my();
var blogModule = (function (my) {
my.AddPhoto = function () {
//添加内部代码
};
return my;
} (blogModule || {}));
(function (my){
my.AddPhoto = function () {
//添加内部代码
};
return my;
})(blogModule || {}));
//调用 blogModule.AddPhoto();
(function(owner) {
//第一个匿名闭包
owner.debug = true;
//Ajax相关参数配置
owner.ajax = {
timeout: 10000,
type: 'post',
dataType: 'json',
};
})(window.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 = {});
(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 = {}));
(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 = {});