Answers for "how to shallow clone javascript class"

0

how to shallow clone javascript class

class myClass {
  constructor() {
    this.str = "String"; //Defining a string
    this.number = 3; //Defining a number
  }
}

var classReference = new myClass(); //Making new instance of class
var myObjectToCopy;

function copyClass() {
  myObjectToCopy = JSON.parse(JSON.stringify(classReference)); //Converting class to a string then turning that string into an object
}

copyClass(); //Calling function to copy the class

//myObjectToCopy is now a copy of classReference
Posted by: Guest on March-28-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language