1

Apologies if the question seems stupid but I'm relatively new to JS.

I have a class Dog that inherits Animal. Animal has an array property. In the code I create a new Dog and add stuff to the array. The problem is that each new instance of Dog seems to share that array.

Animal.js:

define([
  "dojo/_base/declare",
  "evo/common/model/_Model"
  ], function(declare, _Model ) {
  return declare([_Model], {
    _id: 0,
    _items: [],
    _filter: null,
    
    ...
    
  });
});

Dog.js:

define([
  "dojo/_base/declare",
  "evo/common/model/_ModelList"
], function (declare, _ModelList) {
  return declare([_ModelList], {
    
    ...
    
  });
});

I fixed resetting _items when I create a new Dog but I suspect if I had multiple instances of Dog this would affect all. How to make the properties non-static?

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
algiogia
  • 936
  • 2
  • 14
  • 40
  • possible duplicate of [Javascript object members that are prototyped as arrays become shared by all class instances](http://stackoverflow.com/q/4425318/1048572) (assuming you know what the dojo declaration does) – Bergi Jun 11 '16 at 19:12
  • @Bergi not really... It's just been "thrown" at me without much explanation :) – algiogia Jun 12 '16 at 21:06
  • If you're new to JS, maybe you shouldn't start with dojo :-) I'd recommend http://eloquentjavascript.net/1st_edition/chapter8.html as a tutorial, but there are many more. – Bergi Jun 12 '16 at 21:08
  • @Bergi I'e worked with JS in the past but ot was mostly bug fixing. I can't choose the tool to use. The application is developed with dojo and I need to add features to it. Thanks you for the link anyway! – algiogia Jun 13 '16 at 08:18

1 Answers1

3

When creating a dojo class, if its contains arrays or other objects, they should be declared in the constructor() in this way each instance gets its own copy as you expected.

Keep in consideration that in JS simple type like strings, numbers, booleans, null are assigned by value, and are fine to declare in the dojo class.

Instead objects are assigned by reference, including array (which in JS are considered "special" object).

Example:

https://jsfiddle.net/ua3gytbu/

require(["dojo/_base/declare"], function(declare) {
  var Animal = declare(null, {
    constructor: function() {}
  });
  var Dog = declare(Animal, {
    constructor: function() {
         this.items = [];   
    }
  });

  var dog = new Dog();
  dog.items.push(1);
  dog.items.push(2);

  var dog2 = new Dog();
  dog2.items.push(3);

  alert('dog has in items ' + dog.items.length);
  alert('dog2 has in items ' + dog2.items.length);
});
GibboK
  • 71,848
  • 143
  • 435
  • 658