Skip to content

Instantly share code, notes, and snippets.

@zhanglun
Forked from hacke2/clone.js
Last active August 29, 2015 14:08
Show Gist options
  • Save zhanglun/f2bc9662ea1770557285 to your computer and use it in GitHub Desktop.
Save zhanglun/f2bc9662ea1770557285 to your computer and use it in GitHub Desktop.

Revisions

  1. @hacke2 hacke2 created this gist Oct 6, 2014.
    82 changes: 82 additions & 0 deletions clone.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,82 @@
    //浅克隆
    /*Object.prototype.clone = function (){
    var obj = {};
    for(var key in this) {
    if(this.hasOwnProperty(key)) {
    obj[key] = this[key];
    }
    }
    return obj;
    }*/

    //浅克隆测试
    /*var a = {
    name : 'test'
    };
    var b = a.clone();*/


    Object.prototype.clone = function (){
    var obj = {};

    for(var key in this) {
    if(this.hasOwnProperty(key)) {
    if(typeof this[key] == 'function' || typeof this[key] == 'object') {
    obj[key] = this[key].clone();
    }else {
    obj[key] = this[key];
    }
    }
    }

    return obj;
    }

    Array.prototype.clone = function (){
    var arr = [];

    for (var i = this.length - 1; i >= 0; i--) {
    if(typeof this[i] == 'function' || typeof this[i] == 'object') {
    arr[i] = this[i].clone();
    }else {
    arr[i] = this[i];
    }
    };

    return arr;
    }

    Function.prototype.clone = function (){

    var that = this;

    var newFunc = function (){
    return that.apply(this, arguments);
    }

    for (var key in this) {
    newFunc[key] = this[key];
    };

    return newFunc;
    }

    /*var obj = {
    name : 'hehe',
    like : ['man', 'woman'],
    display : function() {
    console.log(this.name);
    }
    };
    var newObj = obj.clone();
    newObj.like.push('other')
    console.log(newObj);
    console.log(obj);*/