jQuery 原理的模拟代码 -4 重要的扩展函数 extend

在上两篇文章中,我们看到每次要通过 jQuery 的原型增加共享方法的时候,都需要通过 jQuery.fn 一个个进行扩展,非常麻烦,jQuery.fn.extend 提供了一个扩展机制,可以方便我们通过一个或者多个示例对象来扩展某个对象。如果没有指定被扩展的对象,那么将扩展到自己身上。

jQuery.extend 也可以通过 jQuery.fn.extend 使用, 在 jQuery 中使用很多,用来为一个目标对象扩展成员,扩展的成员来自于一系列参考对象。

这样,如果我们需要为 jQuery.fn 扩展成员 removeData,就可以这样进行。

jQuery.fn.extend(

{

removeData: function( key ) {

return this.each(function() {

jQuery.removeData( this, key );

});

}

}

);

extend 的源码如下,因为比较简单,所以没有做太多的精简。

1 /// <reference path="jQuery-core.js" />

2

3

4 jQuery.extend = jQuery.fn.extend = function () {

5 // copy reference to target object

6 var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;

7

8 // 深拷贝情况,第一个参数为 boolean 类型,那么,表示深拷贝,第二个参数为目标对象

9 if (typeof target === "boolean") {

10 deep = target;

11 target = arguments[1] || {};

12 // skip the boolean and the target

13 i = 2;

14 }

15

16 // 如果目标不是对象也不是函数

17 if (typeof target !== "object" && !jQuery.isFunction(target)) {

18 target = {};

19 }

20

21 // 如果只有一个参数就是扩展自己

22 if (length === i) {

23 target = this;

24 --i;

25 }

26

27 // 遍历所有的参考对象,扩展到目标对象上

28 for (; i < length; i++) {

29 // Only deal with non-null/undefined values

30 if ((options = arguments[i]) != null) {

31 // Extend the base object

32 for (name in options) {

33 src = target[name];

34 copy = options[name];

35

36 // Prevent never-ending loop

37 if (target === copy) {

38 continue;

39 }

40

41 // Recurse if we're merging object literal values or arrays

42 if (deep && copy && (jQuery.isPlainObject(copy) || jQuery.isArray(copy))) {

43 var clone = src && (jQuery.isPlainObject(src) || jQuery.isArray(src)) ? src

44 : jQuery.isArray(copy) ? [] : {};

45

46 // Never move original objects, clone them

47 target[name] = jQuery.extend(deep, clone, copy);

48

49 // Don't bring in undefined values

50 } else if (copy !== undefined) {

51 target[name] = copy;

52 }

53 }

54 }

55 }

56

57 // Return the modified object

58 return target;

59 };

jQuery 原理的模拟代码 -0 目录