Clone functions deeply

7

I'd like to clone some objects deep. I've seen this question:

Creating a copy of an object in Javascript

... However, none of the answers offers a way to clone a function deeply. In other words, if an array object has functions, its clones will have references to that function.

I'll 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 clone, the clone will have the same Amarelo function, by reference ... And so changing the prototype of the function on an object will also affect its 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.

Is it 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 the changes in their respective prototypes isolated?

    
asked by anonymous 05.09.2017 / 13:38

1 answer

5

Your problem is with Inheritance , you must first define the object:

// Define o objeto
paletaDaltonica[cor] = function() {};

Then you inherit the prototype from the original object using % with_% / a>.

// Herda de: cores[cor]()
paletaDaltonica[cor].prototype = Object.create(cores[cor].prototype);

Reference

See working:

var cores = {
    Amarelo: function () {}
}
cores.Amarelo.prototype.r = 255;
cores.Amarelo.prototype.g = 255;
cores.Amarelo.prototype.b = 0;

var paletaDaltonica = {};
for (var cor in cores) {
  // Define o objeto
  paletaDaltonica[cor] = function() {};
  // Herda de: cores[cor]()
  paletaDaltonica[cor].prototype = Object.create(cores[cor].prototype);
}

paletaDaltonica.Amarelo.prototype.b = 120;
paletaDaltonica.Amarelo.prototype.teste = 'Testando ...'
console.log(cores.Amarelo.prototype, paletaDaltonica.Amarelo.prototype);


var paletaDaltonicaB = {};
// Define o objeto
paletaDaltonicaB.Amarelo = function() {};
// Herda de: paletaDaltonica.Amarelo
paletaDaltonicaB.Amarelo.prototype = Object.create(paletaDaltonica.Amarelo.prototype);
paletaDaltonicaB.Amarelo.prototype.r = 124;
paletaDaltonicaB.Amarelo.prototype.g = 432;
paletaDaltonicaB.Amarelo.prototype.b = 3472;
paletaDaltonicaB.Amarelo.prototype.teste = 'Valor modificado ...'

cores.Amarelo.prototype.b = 200;
console.log(cores.Amarelo.prototype, paletaDaltonica.Amarelo.prototype, paletaDaltonicaB.Amarelo.prototype);
    
15.01.2018 / 18:14