7
I would like to clone some objects in a deep way. I’ve seen this question:
How to create a copy of an object in Javascript
...However, none of the answers offer a way to clone a function in a profound way. In other words, if a matrix object has functions, its clones will have references to that function.
Let me give you an example. With the following object as a starting point:
var cores = {
Amarelo: function () {}
}
cores.getAmarelo.prototype.r = 255;
cores.getAmarelo.prototype.g = 255;
cores.getAmarelo.prototype.b = 0;
If I do a shallow cloning, the clone will have the same function Amarelo
, by reference... And so changing the prototype of the function on an object will also affect your clone. I.e.:
var paletaDaltonica = {};
for (var cor in cores) {
paletaDaltonica[cor] = cores[cor];
}
paletaDaltonica.Amarelo.prototype.r = 120;
// Isso alterou o protótipo de Amarelo no objeto original também.
It is possible to clone a function in a deep way, so that the clone has the same functionality and prototype of the original function, but keeping isolated the changes in their respective prototypes?
Small variation:
paletaDaltonica[cor].prototype = Object.create(cores[cor].prototype);
. The result is the same.– bfavaretto