由jQuery标准插件想到的

天天jQuery之 $.fn

相信大家写过jQuery插件的童鞋都熟悉$.fn.plugin=function(){return this.each(function(){})}. 然后通过选择器得到jQuery Object掉用该方法$(elem).plugin().

问题:

  1. plugin是扩展到$.fn "命名空间',为什么jQuery Object能调用该方法呢
  2. plugin可以无限的扩展到$.fn么

打开jQuery源代码,答案就在下面的几行code中

 

明显的jQuery对象实际上是一个jQuery.fn.init对象

var jQuery = function( selector, context ) {

        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context );
},

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {

  

这里是init方法的定义

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

将jQuery.fn这个Object赋给jQuery.fn.init原型,那么所有的jQuery.fn.init实例都可以使用jQuery.fn Object

 

整理下

  • jQuery实例实际上返回的是jQuery.fn.init实例
  • jQuery.fn.init的原型是jQuery.fn
  • 扩展jQuery.fn
  • jQuery.fn.init的实例就能调用jQuery.fn

按这个原理,写了些测试代码

var A1 = {
   init: function(){  }
}
 
A1.init.prototype = A1;

var iiint = new A1.init();

A1.rg = function(){ alert("rg");}
 
iiint.rg(); // rg被弹出

  

posted @ 2011-08-31 12:50  逆天寒  阅读(265)  评论(0编辑  收藏  举报