davidmarkclements / rfdc

Really Fast Deep Clone
MIT License
635 stars 24 forks source link

Methods not copied over when deep copying a class #29

Open benslv opened 2 years ago

benslv commented 2 years ago

I ran into a bit of an issue today trying to make a deep copy of a class I had. It turns out rfdc doesn't copy over class methods, only its attributes.

Not sure if this is a limitation in JS or a feature that could be added to the package?

I made a minimal reproduction of the issue here:

const clone = require("rfdc")({proto: true});

class TestClass {
    constructor() {
        this.name = "John";
    }

    sayHello() {
        console.log("Hello!");
    }
}

const test = new TestClass()
test.sayHello() // "Hello!"

const testClone = clone(test)
testClone.sayHello() // TypeError: testClone.sayHello is not a function
hood commented 2 years ago

Methods cannot be serialized, so they cannot be "cloned". This would be more of a JS "feature", and it won't happen anytime soon, if ever.

TommyDew42 commented 1 year ago

It would be great if we can document this limitation in the proto session

hood commented 1 year ago

This is not something to document on rfdc's side IMHO. It's completely unrealistic to expect a data serialisation library to be able to serialise logic.

trevor-vaughan commented 1 year ago

The cloneDeep method in lodash could do it but I haven't found anything else that provides a similar capability (yet).

trevor-vaughan commented 1 year ago

Hmm....the clone library also seems to clone objects properly.

@hood Is RFDC a 'cloning' library or a 'serialization' library?