jquery的extend函数

 1 var extend = (function () {
 2 
 3 
 4     var isObjFunc = function (name) {//返回的是一个函数
 5         var toString = Object.prototype.toString
 6         return function () {
 7             return toString.call(arguments[0]) === '[object ' + name + ']'//谁调用函数,就指向谁的上下文;
 8         }
 9     }
10 
11 
12 
13     var isObject = isObjFunc('Object'),
14         isArray = isObjFunc('Array'),
15         isBoolean = isObjFunc('Boolean')
16       // console.log(isObject)//返回的是一个函数
17       // console.log(isArray)
18       // console.log(isBoolean)
19 
20 
21 
22     return function extend() {
23         var index = 0, isDeep = false, obj, copy, destination, source, i;
24 
25 
26         if (isBoolean(arguments[0])) {
27            // console.log(isBoolean(arguments[0]))//true
28             index = 1
29            // console.log(arguments[0])
30             isDeep = arguments[0]//ture
31         }
32 
33         for (i = arguments.length - 1; i > index; i--) {//当i>1的时候,也就是参数值大于1的时候遍历
34             destination = arguments[i - 1]
35             source = arguments[i]
36            // console.log(destination)//{name:3}
37            // console.log(source)//{name:3}
38 
39 
40             if (isObject(source) || isArray(source)) {//如果是数组或者对象;
41                // console.log(source)
42                 for (var property in source) {
43                     obj = source[property]
44 
45                     if (isDeep && (isObject(obj) || isArray(obj))) {//如果是数组或者对象;
46                         copy = isObject(obj) ? {} : []
47                         var extended = extend(isDeep, copy, obj)
48 
49                         destination[property] = extended//目标的就等于深拷贝的;
50 
51                     } else {
52 
53                         destination[property] = source[property]//如果是值类型的;直接等于原来的;
54                     }
55                 }
56             } else {//如果不是数组或者对象
57                 destination = source
58             }
59         }
60         return destination//返回目标对象
61     }
62 })()
63 
64 
65 var a = {name: 1}
66 var b = {name: 2}
67 var c = {name: 3}
68 extend(true, a, b, {name: [a, b, c], value: a})
69 console.log('-----------------------')
70 console.log(a)//{name:Array(3)}
71 console.log(a.name[0] === a) // false
72 console.log(a.value === a) // false

 

posted @ 2018-09-17 09:14  前端极客  阅读(153)  评论(0编辑  收藏  举报