How do you copy an object, preserving its prototype, without running the constructor?
Everything below is context if you're wondering why I want to do such a thing, feel free to ignore it and answer the question.
I'm just experimenting with bringing RAII/ownership concepts into javascript (for fun and curiosity). Surprisingly, I have a solution for destructors that works quite well, but I'm actually stumbling on copy constructors and move constructors.
Specifically, I have a class FileIO
:
class FileIO {
constructor(filename) {
this.connection = new FileConnection(filename);
}
destructor() {
this.connection.close();
}
move() {
const copy = _how_do_I_(); //copy of this, without running constructor().
copy instanceof FileIO; // should be true
// move connection to copy
copy.connection = this.connection;
this.connection = null;
return copy;
}
write() {/* TODO */}
read() {/* TODO */}
}
Ideally, I would be able to do this:
function main() {
const fileIO = new FileIO("./something.txt");
useTheFile(fileIO.move());
}
You can see, I don't want to do copy = {...this}
because it won't be an instance of FileIO anymore. Also, I can't do copy = new this.constructor(...)
because I don't want to duplicate the file connection. Is this even possible?
Thank you.