$.extend()的实现源码 --(源码学习1)

目标:

$.extend({

        add:function(a,b){

            return a + b;

        }

    })

console.log($.add(1,2));

是怎么实现可以将add函数挂在jQuery后面?

jQuery -v1.12.4

 1 jQuery.extend = jQuery.fn.extend = function() {
 2     var src, copyIsArray, copy, name, options, clone,
 3         target = arguments[ 0 ] || {},
 4         i = 1,
 5         length = arguments.length,
 6         deep = false;
 7
 8     // Handle a deep copy situation
 9     if ( typeof target === "boolean" ) {
10         deep = target;
11
12         // skip the boolean and the target
13         target = arguments[ i ] || {};
14         i++;
15     }
16
17     // Handle case when target is a string or something (possible in deep copy)
18     if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
19         target = {};
20     }
21
22     // extend jQuery itself if only one argument is passed
23     if ( i === length ) {
24         target = this;
25         i--;
26     }
27
28     for ( ; i < length; i++ ) {
29
30         // Only deal with non-null/undefined values
31         if ( ( options = arguments[ i ] ) != null ) {
32
33             // Extend the base object
34             for ( name in options ) {
35                 src = target[ name ];
36                 copy = options[ name ];
37
38                 // Prevent never-ending loop
39                 if ( target === copy ) {
40                     continue;
41                 }
42
43                 // Recurse if we‘re merging plain objects or arrays
44                 if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
45                     ( copyIsArray = jQuery.isArray( copy ) ) ) ) {
46
47                     if ( copyIsArray ) {
48                         copyIsArray = false;
49                         clone = src && jQuery.isArray( src ) ? src : [];
50
51                     } else {
52                         clone = src && jQuery.isPlainObject( src ) ? src : {};
53                     }
54
55                     // Never move original objects, clone them
56                     target[ name ] = jQuery.extend( deep, clone, copy );
57
58                 // Don‘t bring in undefined values
59                 } else if ( copy !== undefined ) {
60                     target[ name ] = copy;
61                 }
62             }
63         }
64     }
65
66     // Return the modified object
67     return target;
68 };

分析:

第3行:取到函数add

第23-26行:将this也就是jquery的实例对象,function(selector, context){} 赋值给target.

第31行:将函数add赋值给options,并进行遍历。

第36行:将options = { add:function(a,b){   ... }}的函数赋值给copy.

第60行:通过target[name]=copy; 将jquery的实例添加一个属性add 就成了jQuery[‘add‘]=function (a,b){ return a+b};

时间: 2024-10-09 01:53:07