1. [代码]方法代码
function cp(source, target) {
function isBaseType(v) {
var type = typeof v;
var basetype = {
"string": true,
"number": true,
"boolean": true,
"function": true,
"undefined": true
};
return basetype[type] || v === null;
}
function createClone(v) {
var clone = [];
if (!(v instanceof Array)) {
clone = {};
}
return clone;
}
function createCloneFn(fn) {
var fncode = fn.toString();
var regex_params = /^function\s+?(\()([\s\S]*?)(\))/;
var params = [];
var params_index = 2;
var result = fncode.match(regex_params);
if (result) {
var param_code = result[params_index];
if (param_code) {
params = param_code.split(",")
}
}
var fncode = fncode.replace(regex_params, "").replace(/^\s*?\{|\}\s*?$/g,"");
fncode += " console.log(‘clone‘)";
params.push(fncode);
return Function.apply(null, params); ;
}
function createVal(v)
{
var val = v;
if( typeof v =="function" )
{
val = createCloneFn(v);
}
return val ;
}
if (source instanceof Function) {
target = createCloneFn(source);
} else if (source instanceof Array) {
if (target instanceof Array) {
var source_size = source.length;
for (var index = 0; index < source_size; index++) {
var item = source[index];
if (!isBaseType(item)) {
var clone_array = createClone(item);
target.push(clone_array);
arguments.callee(item, clone_array);
}http://www.huiyi8.com/jiaoben/?
//基础类型
else {jQuery特效
target.push( createVal(item));
}
}
} else {
//console.log("数组拷贝不成立");
}
} else if (typeof source == "object") {
if (!isBaseType(target))
for (var attrname in source) {
var val = source[attrname];
//是否为基础类型
if (!isBaseType(val)) {
var clone_obj = createClone(val);
target[attrname] = clone_obj;
arguments.callee(val, clone_obj);
} else {
target[attrname] = createVal(val);
}
}
}
return target;
}
2. [广告代码]测试代码
var target = [];
var source = [
[{
a: {
"show": function() {
alert(1)
}
}
}]
];
target =cp(source, target);
Javascript对象拷贝(clone)