You cannot clone a class in javascript. Lets take a look at this example:
function classCloner(x) {
var constructor = function() {
if(!(this instanceof constructor)) throw new TypeError("Not a constructor");
x.apply(this, Array.prototype.slice.call(arguments));
}
for(var attr in x) {console.log(attr);
if(Object.hasOwnProperty(attr)) constructor[attr] = x[attr];
}
constructor.prototype = Object.create(Object.getPrototypeOf(x.prototype));
for(var attr in x.prototype) {
if(Object.hasOwnProperty(attr)) constructor.prototype[attr] = x.prototype[attr];
}
return constructor;
}
This function doesn't work:
- ECMA6 classes uses checks in the constructor and member functions, so that you cannot directly invoke the class without new. It checks if
this instanceOf constructor
- If you clone a class, you need to clone all properties. Many properties are functions and they only work with one type, creating multiple types could cause weird errors.
Still there is a way to clone an ECMA6 class, using eval.
var clonedClz = eval(oldClz.toString());
This will clone all properties of the class, and will clone all functions. When oldClz is modified after it was created (e.g oldClz.foo = () => 'bar'
), then that change will not apply to the cloned class.
This works, only for ecmascript6 classes, and not for plain js classes. Creating multiple types with the same functions can cause big issues.