Chinaunix首页 | 论坛 | 博客
  • 博客访问: 367538
  • 博文数量: 284
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1707
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-14 16:38
文章分类

全部博文(284)

文章存档

2015年(6)

2014年(278)

我的朋友

分类: JavaScript

2014-07-05 15:49:51


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);
                }
                //基础类型
                else {
                    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);

阅读(413) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~