首页 > 代码库 > 通过jQuery源码学习javascript(二)

通过jQuery源码学习javascript(二)

  1. 匿名函数

(function(window, undefined){

})(window)

   传入window变量的原因:使window由全局变量变为局部变量,不需要将作用域链退回到顶层作用域,以便更快的访问window。

   在参数列表增加undefined的原因:在自调用匿名函数的作用域内,确保undefined是真的未定义。

  好处:

          创建私有命名空间,函数体内的方法和变量不会影响全局空间,不会和其他程序的变量和方法冲突,就是传说中的不污染全局变量。

   2.  功能扩展。

(function(window, undefined){
    var jQuery = function()
    {
        return new jQuery.fn.init();
    }
    jQuery.fn = jQuery.prototype = {
        
        version: ‘1.8.3‘,
        init: function()
        {
            return this;
        }
    }
    jQuery.fn.init.prototype = jQuery.fn;
    jQuery.extend = jQuery.fn.extend = function(obj){

        for(var n in obj)
            this[n] = obj[n];
        return this;
    }
    jQuery.fn.extend({
        test: function(){
            console.log(‘hello world!!‘);
        }
    });
    window.jQuery = window.$ = jQuery;

})(window)


   


通过jQuery源码学习javascript(二)