首页 > 代码库 > 通过jQuery源码学习javascript(二)
通过jQuery源码学习javascript(二)
匿名函数
(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(二)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。