|
|
今天想做树形导航栏,查找了资料,找到了一个框架,比较小所以研究其中的代码,发现第一句话就把我难住了,主角是——jQuery.fn。
在此,再次停住,只好继续找资料,现在整理下自己所理解到的知识。
一,jQuery.fn是什么
答:从jqurey源代码,如下小段:
jQuery.fn = jQuery.prototype = {constructor: jQuery,init: function( selector, context, rootjQuery ) {............} }
可以看出,jQuery.fn == jQuery.prototype, 即jQuery.fn是 jQuery.prototype别称。
在这里我们停一下,说说让我还一直头疼的prototype属性或对象,怎么说呢,prototype属性或对象就相当于一个指针,指向某个object,这个object就可以称为子类对象的原型,那么我们可以间接地访问指向object的属性跟方法,也就差不多当前对象继承的指向的某个object。这里有个问题,就是如果指向的某个object有属性跟当前对象的属性相同的话怎么办,很简单,一句话——就近原则,从当前对象找,找到返回,没有去prototype指向的object里面找,没有在去prototype指向的object的prototype指向的object找,一层一层地找下去,知道找到为此。例子如下
<script type="text/javascript">var animal = function(){this.name= "dfsdfsdf";this.sex= 'male';};var a = new animal();alert(a.name);var cat = function(){ this.play = function (){ alert('cat play') }; }; cat.prototype = new animal(); cat = new cat(); alert(cat.name);cat.name = "ddd";alert(cat.name);</script>
头疼到此,接回,继续jQuery.fn
从上面里面也可以看出prototype就相当于给某个类添加属性或者方法,那么,这样的话,我们就可以逆推一下下, jQuery.prototype——》jQuery.fn就是给jQuery类添加新的属性或者方法,来,我们来看下,材料如下:
//给jQuery打洞,新添的方法$.fn.extend({sayHello: function(){$(this).click(function(){alert("hello jquery!");});}});//html代码<input type="button" value="sayHello" id="sayHello"/>//使用我们给jQuery新添的方法$(function(){$('#sayHello').sayHello();//这个我们可以弹出hello jquery!});
到此,可以认识Query.fn了
接下来,脑补一下,类似的知识jQuery.extend(object);这个方法
不错,它扩展的方法就是米饭,可以直接用,是jQuery类的静态方法。
$.extend({add: function(a,b){return a + b ;}});alert($.add(3,4));//piapia出来个7
意想得到吧,OK,到此over,继续那小插件去鸟。
我是菜鸟,请拍砖。 |
|