1

In prototype.js you can create classes e.g. like this:

var MyClass = Class.create(
{
    initialize: function (par1, par2)
    {
        this.data = $R(par1, par2).toArray();
    }
});

and instantiate them through

var myObj = new MyClass(1, 7000);

Now, how can I copy this object? The following does not work:

var myObj2 = MyObj.clone();

In my specific case, I only need a shallow copy, i.e. the attributes of the instance can reference the same objects. Some way of defining a copy constructor would certainly be the most versatile option.

Is that possible? (Preferably without relying on prototype.js internals)

bodo
  • 1,005
  • 15
  • 31
  • 1
    `var myObj2 = Object.create(myObj)` – Rajaprabhu Aravindasamy Mar 20 '16 at 11:36
  • @RajaprabhuAravindasamy: That's less-than-shallow – Bergi Mar 20 '16 at 11:41
  • @Bergi: I don’t think this is a duplicate. Notice that I inquire about the class system of the prototype.js framework, not general javascript objects. – bodo Mar 20 '16 at 12:14
  • @canaaerus: If I understood you correctly, you wanted to do it without prototype.js, so it's just a standard js object to copy? – Bergi Mar 20 '16 at 12:16
  • @RajaprabhuAravindasamy: Thank you – that seems to work. (Even though Object.create is not specific to prototype.js) Maybe you could add this as an answer together with a short explanation. – bodo Mar 20 '16 at 12:17
  • @Bergi: I meant without internals / implementation details, i.e. just using the prototype.js API. But a simplistic solution like Raj’s is close enough. – bodo Mar 20 '16 at 12:18
  • @canaaerus Ah, I see – Bergi Mar 20 '16 at 12:20

1 Answers1

2

You can use Prototype's Object.extend (or the native ES6 Object.assign) to copy your properties onto a new instance of your class:

var MyClass = Class.create({
    initialize: function (par1, par2) {
        this.data = $R(par1, par2).toArray();
    },
    clone: function() {
        return Object.extend(Object.create(Object.getPrototypeOf(this)), this);
    }
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375