1

I've tried lots of solution that I've found in here, but until now any of them really solved my problem.

Let's say that I have a function like this:

    var SquareObject = function(id, x, y, text, rectClass, textClass){
      var arrayObj = {
        "id": null,

        "shape": "rect",

        "label": null,

        "rect": {
          "class": null,
          "x": null,
          "y": null,
          ...
        },

        "text": {
          "class": null,
          "x": null,
          "y": null,
          ...
        }

        function initArrayObj(){
          ...
        }

        function anotherFunction(){
          ...
        }
    }

How can I copy everything, including the methods? Because after I make a copy of this SquareObject I'll have to change the properties located at arrayObj, while still maintaining a copy of its original state.

I've found ways of cloning just the content of arrayObj, but right now that doesn't fully solve my problem.

Thanks!

416E64726577
  • 2,214
  • 2
  • 23
  • 47
  • Duplicate? http://stackoverflow.com/questions/1833588/javascript-clone-a-function – Derek 朕會功夫 Jun 18 '14 at 20:07
  • What exactly are you trying to "clone"? `SquareObject` is a function with several local variables - you can't clone them all at once. Where are you trying to clone to? – Ian Jun 18 '14 at 20:24
  • I've tried all the solutions from that topic before. The thing is my function won't return anything, it is acting like an Object from OOP languages. – Filipe Belatti Jun 18 '14 at 20:25
  • @Ian , let's say that I have something like "var square1 = SquareObject", than I would need "var square2 = clone(SquareObject)", in a way that I could change the variables from square2, without changing them in square1. But if you're saying that I can't clone everything at once I think that I'll have to change my approach. – Filipe Belatti Jun 18 '14 at 20:28

2 Answers2

0
var copyObj = arrayObj.constructor();
for (var attr in arrayObj) {
    if (arrayObj.hasOwnProperty(attr)) {
        copyObj[attr] = arrayObj[attr];
    }
}
anmorozov23
  • 2,395
  • 1
  • 11
  • 3
0

If you want to copy the function as it is

var obj= Object.assign(SquareObject)
console.log(obj)

If you want to copy a constructor then

Person(){
  this.age=20;
  this.name='ignatius';
  this.display = function(){
    console.log(`Name : ${this.name}  ${this.age}.`);
 }
}

var copy = Object.assign(Person);
var obj = new Person();

console.log(obj.name)// 'ignatius'

This also works for objects.

var a= {
          name: 'ignatius',
          age: 2
  }

var copy = Object.assign(a)

console.log(a.name ) // ignatius
Ignatius Andrew
  • 8,012
  • 3
  • 54
  • 54