Cloning functions in a deep way

Asked

Viewed 92 times

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?

1 answer

5


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

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

Then you inherit the prototype of the original object using Object.create.

// 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);

  • 1

    Small variation: paletaDaltonica[cor].prototype = Object.create(cores[cor].prototype);. The result is the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.