JS简单粗暴地实现浅克隆

来源:互联网 发布:网络规划与设计题库 编辑:程序博客网 时间:2024/06/13 10:41

1.实现:

    var ObjectUtil = (function() {        function clone(obj) {            var json = JSON.stringify(obj);            var newObj = JSON.parse(json);            return newObj;        }        return {            clone: clone,        }    })();

2.测试:

    var obj = {        name: "leo",        age: 18    }    var obj2 = ObjectUtil.clone(obj);    obj.age = 30;    obj2.age = 20;    console.log(obj);//Object {name: "leo", age: 30}    console.log(obj2);//Object {name: "leo", age: 20}

借助JSON实现,简单粗暴实现浅克隆大笑

0 0
原创粉丝点击