龙空技术网

js Object扩展extend方法

洲游历累 274

前言:

当前你们对“js object”大概比较看重,兄弟们都想要分析一些“js object”的相关知识。那么小编在网络上网罗了一些对于“js object””的相关资讯,希望各位老铁们能喜欢,大家快快来学习一下吧!

这个扩展的方法类似于jquery中的extend方法.具体扩展写法如下:

Object.extend = function (target, source, 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] = arguments.callee(src ||(copy.length != null ? [] : {}), copy, deep); else if (copy !== undefined) target[name] = copy; } } i++; } return target; };

调用如下:

var source = { id: 1, name: 'Jack Source' };var target = { name: 'Jack Target', gender: 1, tel: { homeTel: "158255", officeTel: "02112585"} };var newObj1 = Object.extend(target, source); for (var key in newObj1) { document.write("key:" + key + "===value:" + newObj1[key] + "<br/>"); for (var childs in newObj1[key]) document.write("childs:"+childs+"=======value:"+newObj1[key][childs]+"<br/>"); }

标签: #js object #jqueryextend原理 #扩展jquery函数功能 #jqueryobjinit