Javascript: how to copy a object and keep its prototype chain?

1.5k views Asked by At

I have an object:

var obj = {
     name: "Mike"
}

// and its prototype property:
obj.__proto__:
   say: function () {...}
   walk: function () {...}

I want copy it and keep the __proto__

first I thought jQuery $.extend method:

$.extend({}, obj)

but what is return would merge the __proto__ like:

{
    name: "Lee",
    say: function () {},
    walk: function () {}
}

so how can I copy the object with keep the prototype chain?

1

There are 1 answers

2
Mics On

Firet of all, what kind of copy do you want? Deep copy or shallow copy? Assume that you want shallow copy; just copy src's own properties(unless dest already has same property) and __proto__ to dest.

function copy(dest, src) {
    var p;
    for (p in src) {
        if (src.hasOwnProperty(p) && !dest.hasOwnProperty(p)) {
            dest[p] = src[p];
        }
    }
    dest.__proto__ = src.__proto__;
}

Fiddle: http://jsfiddle.net/U6uY4

If you want deep copy, replace for .. in loop to deep copy algorithm that fits with your use case.


Note that this is uncommon requirement. I suggest you think again what do you really want to do.