读jquery之一(jquery对象的组成)
转自:http://snandy.iteye.com/blog/547429
以下是jquery 1.3.2 代码片段
- ...
- jQuery = window.jQuery = window.$ = function( selector, context ) {
- return new jQuery.fn.init( selector, context );
- };
- jQuery.fn=jQuery.prototype={
- init:function(){...},
- ...
- }
- jQuery.fn.init.prototype = jQuery.fn;
- ...
初看上去像是在用原型方式 定义一个类jQuery($),但实际我们使用时是函数调用$("#id"),却不是new $("#id")。
function jQuery中new了一个function init的实例,然后返回。见具名函数的调用方式(3) 。jquery写的实在诡异,它把init又挂在了function jQuery的prototype上,阅读起来有些绕人。
jQuery.fn.init.prototype = jQuery.fn; 是关键的一句。该句把function jQuery的原型赋值给了function init的原型。当调用$("#id")时返回的对象组成包括两个部分。
1,由function init中this带的(如length,context);
2,由function jQuery的prototype带的(如size,each,attr等方法);
模仿jQuery来写一个
- function $(selector){
- return new $.prototype.init(selector);
- }
- $.prototype={
- init:function(selector){
- if(selector.nodeType==1){
- this[0] = selector;
- }else{
- this[0]=document.getElementById(selector);
- }
- this.length=1;
- },
- attr:function(name,value){
- this[0].setAttribute(name,value);
- return this;//链式调用
- },
- hide:function(){
- var self=this;
- setTimeout(function(){
- self[0].style.display="none";
- },3000);
- return this;//链式调用
- }
- }
- $.prototype.init.prototype=$.prototype;
简单起见,这里$只传html element或元素id,this上挂了length属性,赋值为1。当我们如下调用时
- var obj = $();
- console.dir(obj);
这行代码实际没有什么意义,只是为了测试调用后obj的组成。firebug控制台输出如下:
length:0;
init:function
attr:function
hide:function
即obj对象是由function init中this及function $.prototype组成的。
测试下$.prototype上的方法(假设页面body添加了id=content):
- $("content").attr("bgcolor","red").hide();
先调用attr添加了id=content属性,稍候就隐藏了。
总结下:
jquery对象指的是jQuery.prototype.init的实例,简单的说就是new jQuery.prototype.init。
这里jQuery.prototype.init的类型是function,可以看成是一个类。源码中如下:
- jQuery = window.jQuery = window.$ = function( selector, context ) {
- return new jQuery.fn.init( selector, context );
- },
jQuery对象由以下部分组成:
1,挂在jQuery.prototype.init中的this上的属性或方法。
2,挂在jQuery.prototype.init.prototype上的属性或方法。
3,因为把jQuery.prototype赋值给了jQuery.prototype.init.prototype,所以挂在jQuery.prototype上的属性和方法也jQuery对象的一部分。
4,通过jQuery.fn.extend({...})方式扩展的属性或方法。(见下一篇)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述