2

I'm writing clone method for a Config class:

abstract class ParentConfig {
    id: string | undefined;
    name: string = '';
}

export class Config extends ParentConfig {
    version: number | undefined;
    constructor() {
        super();
    }

    clone = (): Config => {
        const config = new Config();
        Object.assign(config, JSON.parse(JSON.stringify(this))); // this.version is undefined!!!
        return config;
    }
}

const firstConfig = new Config();
firstConfig.name = 'first';
firstConfig.version = 1;

const secondConfig = firstConfig.clone();
secondConfig.version;// undefined

Before calling clone, I can see in the Dev tool that Config instance has a proper version but new returned Config has undefined version.

Any ideas?

StardustGogeta
  • 3,331
  • 2
  • 18
  • 32
Mhd
  • 2,778
  • 5
  • 22
  • 59
  • 4
    Side note: `JSON.parse(JSON.stringify(this))` is a **lossy, slow** way to copy an object. – T.J. Crowder Jul 31 '19 at 14:08
  • 1
    [Works for me](http://www.typescriptlang.org/play/#code/IYIwzgLgTsDGEAJYBthjAgCsKBTAdhAMID2+AZgJYDmCA3gLABQCClAJgFwKRSX60APggCu+drir5c7ANzNW+YAFtc3Xv1oBeBAHJd8pgF9mzFGgykKNBLgAeEAuwzY8hK1VqMWCAG64oMEoybnwRZRAAhGExCSkZQ1ZYMl4ReBIoAAoASnoFVh4RAAcAnMSEEyZ8lDJcBB0c7g8bLQA+PJ8klMRk620EaQB3BGbqMvzWAHkQACtceAA6Cxp8TN7PABoEACkAZUmAOQWinDBcTL3DhY0BSnIAT0yIAAtKMGyP2QQAem+EF7eC38gWC+DYGFikn4MgAhHCJgg8BARFAwesaOVKpUzN0EFRAsQyJ56gNcMNRuMmPjIKMFkpVCTdNSIAZmMzacCgmQSQBGQw4-CQHjzMjsUYk9lEmgLGrSSm9MAkZC4BbIEhjM69MVS6hAgJc-DZWS-UTiKHSdhAA) (open the console to see the result). – T.J. Crowder Jul 31 '19 at 14:10
  • 1
    (I don't see why `clone` should be an arrow function instead of a method, though.) – T.J. Crowder Jul 31 '19 at 14:11
  • @T.J.Crowder any suggestion for clone? – Mhd Jul 31 '19 at 14:37
  • 1
    For a shallow copy of enumerable, own properties: `return Object.assign(new Config(), this);`. For deep copies, see the answers to [this question](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript). – T.J. Crowder Jul 31 '19 at 14:41

0 Answers0