As I was implementing my undo in my project I stumble upon a problem. When I would clone or copy a class Object even with a deep clone.
It will not clone the local variables. Well that's a problem and would even say that's a flaw in JS if it's not a bug. (Like the imaginary math I suppose.)
In case you don't know. A local var of a class in JS is a like a member that doesn't have the prefix this. in front of it.
Example:
class MultiEpisode {
constructor(ThisFilename = "", ThisMediaText = ""){
let MeBeLocalObj = {"SomeObject":GetElementById("Whatever")};
let MeBeLocalArray = [1,2,3];
let MeBeLocalVar = 10;
let MeBeLocalString = "Hello Morons";
// NOW this "MeBeLocal" will simply not exist in a normal Cloning/copy.
// It will simply point to the original. So changing the state of one is applied to all cloned
// That has the potential to be a major issue. How come nobody ever consider that.
// The only way this "MeBeLocal" will exist is by making a new instance of that Class.
// A cloning won't do. Just keep this in mind.
}
}
What's The solution:
The best way I found and let me know if you have a better idea.
Is to have a public member that Clone/Copy itself.
Basically, you also need a Public function that will export all the internals/locals.
In other word: Make them public sort of.
Something that would look like this:
this.GetInternals = function (){
return {MeBeLocalObj, MeBeLocalArray, MeBeLocalVar, MeBeLocalString};
}
this.CloneInternals = function (That){
let ThatInternals = That.GetInternals();
MeBeLocalObj = ThatInternals.MeBeLocalObj;
// This will only point to the original, if you want a real copy
MeBeLocalObj = CopyObject(ThatInternals.MeBeLocalObj);
MeBeLocalArray = CopyArray(ThatInternals.MeBeLocalArray);
// Or if that object also a Complex class with lots of locals
// you may have to implement it's cloning too.
MeBeLocalObj = ThatInternals.MeBeLocalObj.Clone();
// And if this go on. You will have hours of fun if not days, ahead of you.
// These do not need a full copy. Already a copy.
MeBeLocalVar = (ThatInternals.MeBeLocalVar);
MeBeLocalString = (ThatInternals.MeBeLocalString);
}
this.Copy = function(){
let ThisClone = new MultiEpisode(ThisFilename);
ThisClone.$CLONED = true;
ThisClone.CloneInternals (this);
return ThisClone;
}
I am assuming you know how to do a simple CopyObject and a simple CopyArray.
If you don't and need a full working example. Let me know in the comments and I'll make a CodePen about it.
Those are not private member variables as they are not members of the class. They are local variables, scoped to the constructor.