var
// Define a local copy of jQuery
// jQuery 即 jQuery()这个函数,即 $()这个函数
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// init的返回值,即jQuery的返回值
// 第7篇中我们分析了这行代码,等同于:
// var ret = {};
// jQuery.fn.init.apply(ret,selector, context, rootjQuery);//以ret为上下文调用init方法
// ret.prototype = jQuery.fn.init.prototype; //jQuery.fn.init.prototype随后会被赋值为 jQuery.fn,这句好关键
// return ret;
return new jQuery.fn.init( selector, context, rootjQuery );
},
// jQuery.fn 是对jQuery原型的引用,原型中定义了init函数
jQuery.fn = jQuery.prototype = {
init: function( selector, context, rootjQuery ) {
//...
// init 函数返回的是 this[0]、this[1]方式返回的数组,是执行选择器的结果
return jQuery.makeArray( selector, this );
}
}
;
// Give the init function the jQuery prototype for later instantiation
// 将jQuery.fn设置为jQuery选择
jQuery.fn.init.prototype = jQuery.fn;在笔记的第2篇我们学习过,给对象的原型增加属性或方法,对象也会自动获得这些方法。
<div id='x'>Bill</div>
<script>
jQuery.fn.extend({
greeting:function(){
console.log('Hi, buddy! I am hailong\'s friend ' + this.text());
}
});
$('#x').greeting();// Hi, buddy! I am hailong's friend Bill
$.greeting();//error : no such method
</script><div id='b'>Bill</div>
<div id='s'>Steven</div>
<script>
jQuery.fn.extend({
lord : 'liuhailong ',
name : 'jQuery Object'
});
console.log($('#b').lord); // output : liuhailong
console.log($('#b').name); // output : jQuery Object
var b = $('#b'), s = $('#s');
b.name = 'Bill';
s.name = 'Steven';
console.log(b.name,s.name); // output : Bill Steven
</script>Java程序员的JavaScript学习笔记(11——jQuery-在“对象”层面扩展)
原文地址:http://blog.csdn.net/stationxp/article/details/40497837