I am asking for good practices showing how to create a converting constructor in Javascript with the correct chain of prototypes.
It should: - get the existing object as a parameter - return a new class type object that contains all the properties of the old class - add new properties - change some of the properties
I want to avoid manually rewrite all properties.
If someone has a reference to examples of good practices creating other types of constructors and their inheritance, this can be helpful.
Right now working (but ugly) solution is here:
//Function from ( https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object )
function deepClone(obj)
{
var copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = deepClone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = deepClone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
function A()
{
this.param1 = {'a': 1};
this.param2 = 'b';
}
A.prototype.getParam1 = function()
{
return this.param1;
}
function B(objectToCopyFrom)
{
//Code to copy all properties from the objectToCopyFrom and inherite prototype.
Object.assign(this, deepClone(objectToCopyFrom));
this.param1.a += 2;
this.param3 = 'c';
}
B.prototype = Object.create(A.prototype);
B.prototype.getParam3 = function()
{
return this.param3;
}
var a = new A();
a.param1 = {'a': 2};
var b = new B(a);
console.log(b.param3); //Should print: "c"
console.log(JSON.stringify( b.getParam1() )); //Should print: "{'a': 4}"
a.param1.a = 8;
console.log(JSON.stringify( b.getParam1() )); //Still should: "{'a': 4}"
https://jsfiddle.net/7h1gatom/6/
Please help me do it in a better, cleaner way without ES6 if it is possible.