首页 > 其他 > 详细

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

时间:2016-06-03 18:38:47      阅读:210      评论:0      收藏:0      [点我收藏+]
目标:
$.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};
 
 

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

原文:http://www.cnblogs.com/zqzjs/p/5557091.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!