---
title: "Java程序员的JavaScript学习笔记（11——jQuery-在“对象”层面扩展）"
author: "stationxp"
date: "2014-10-27T04:07:00Z"
tags: []
slug: "java-javascript-11-jquery"
draft: false
lastmod: "2014-10-27T13:19:27Z"
id: 2148226
url: "https://stationxp.iteye.com/blog/2148226"
---

计划按如下顺序完成这篇笔记：  
1\. 理念。  
2\. 属性复制和继承。  
3\. this/call/apply。  
4\. 闭包/getter/setter。  
5\. prototype。  
6\. 面向对象模拟。  
7\. jQuery基本机制。  
8\. jQuery选择器。  
9\. jQuery工具方法。  
10\. jQuery-在“类”层面扩展。  
11\. jQuery-在“对象”层面扩展。  
12\. jQuery-扩展选择器。  
13\. jQuery UI。  
14\. 扩展jQuery UI。  
这是笔记的第11篇，我们将对$()返回的对象功能进行扩展，以丰富其属性和功能，满足我们的需要。  
在第9篇（http://blog.csdn.net/stationxp/article/details/40480185）我们了解到jQuery.extend和jQuery.fn.extend其实定义相同。  
调用者不同，才导致了两个函数功能的差别(详细机制请参见本笔记第3篇)。  
上一篇我们研究了jQuery.extend，本篇重点研究jQuery.fn.extend。

/*  
作者博客：[http://blog.csdn.net/stationxp](http://blog.csdn.net/stationxp)  
作者微博：[http://weibo.com/liuhailong2008](http://weibo.com/liuhailong2008)  
转载请取得作者同意  
\*/

# 1、jQuery.fn.extend扩展了谁？

jQuery.fn.extend({});  
上面语句调用者是jQuery.fn，jQuery.fn是谁？  
看下面的jQuery源码：

```
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;
```

以上代码，简而言之，jQuery.fn是$()函数返回值的原型对象。

在笔记的第2篇我们学习过，给对象的原型增加属性或方法，对象也会自动获得这些方法。

# 2、试试看

## 2.1、扩展方法

```
<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>
```

## 2.2、可以扩展属性吗？

```
<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>
```

正如我们期待的：完美支持。

# 3、可以做什么？

有什么用？可以实现任何你想实现的功能，发挥你的想象力吧！