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?
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(unlessdest
already has same property) and__proto__
todest
.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.