stampit-org / stampit

OOP is better with stamps: Composable object factories.
https://stampit.js.org
MIT License
3.02k stars 102 forks source link

array in props persist across instances of stamp #349

Closed ilan-deepreach closed 4 years ago

ilan-deepreach commented 4 years ago
var stampit = require("stampit")

var b = stampit({props: {a: []}, init() {console.log(this.a);this.a.push(1); console.log(this.a)}})
b();
b();
b();

what's logged is [1] then [1, 1] then [1, 1, 1] I expect [1] consistently. Why would props be shared between objects that are instance of stamps.

koresar commented 4 years ago

Hello. This is by design.

To solve your problem you can create that array every time for every new object instance.

stampit({
  init() {
    this.a = [];
  }
});

Or, better, in this case use the deepProps:

stampit({
  deepProps: []
});

The props are always copied by reference. That's by design. (Same as in classes.)

Whereas the deepProps are always (deeply) cloned.