Javascript的对象复制
http://www.iteye.com/topic/1130308
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
Js代码 var source={ a:10, b:20, c:'zhongguo', d:['abcd','efg',10], e:function(){ alert(1); }, } function copy(s,d){ if(s instanceof Object){ for(var p in s){ if(p instanceof Object){ copy(s[p],d[p]) }else{ d[p]=s[p] } } }else{ d=s; } } var d={}; copy(source,d) console.info(d); d.e(); |
http://www.jb51.net/article/21202.htm
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
Js代码 /* * @param {Object} target 目标对象。 * @param {Object} source 源对象。 * @param {boolean} deep 是否复制(继承)对象中的对象。 * @returns {Object} 返回继承了source对象属性的新对象。 */ Object.extend = function(target, /*optional*/ source, /*optional*/ deep){ target = target || {}; var sType = typeof source, i = 1, options; if (sType === 'undefined' || sType === 'boolean') { deep = sType === 'boolean' ? source : false; source = target; target = this; } if (typeof source !== 'object' && Object.prototype.toString.call(source) !== '[object Function]') source = {}; while (i <= 2) { options = i === 1 ? target : source; if (options != null) { for (var name in options) { var src = target[name], copy = options[name]; if (target === copy) continue; if (deep && copy && typeof copy === 'object' && !copy.nodeType) target[name] = this.extend(src || (copy.length != null ? [] : {}), copy, deep); else if (copy !== undefined) target[name] = copy; } } i++; } return target; }; |
测试代码
|
1 2 3 |
Js代码 var source = {id:1, name:'Jack Source'}, target = {name:'Jack Target', gender:1,tel:{homeTel:"158255",officeTel:"02112585"}}; var newObj1 = Object.extend(target, source); |
