-1

I have created a javascript class. When I create instances using the new keyword, I don't know why all of the instances share the same array data.

Can anybody explain why this happens? The Cards array in this example is referenced by all instances I created:

(function (scope) {
    //Player class: player information, graphics object
    //Contructor: init properties
    function Player(opts) {
        //INITIALIZE PROPERTIES
        this.initialize(opts);
    }

    Player.prototype = {
        AccountID: '',
        Position: -1,
        UserName: '',
        Level: 0,
        Avatar: 'av9',
        Gold: 0,
        Cards: [],
        pos: { x: 0, y: 0 },
        graphicsObj: {},
        assets: {},
        Status: 0,

        initialize: function (opts) {
            //copy all properties to new instance       
            this.copyProp(opts);

            this.setCards();
            this.createGraphicObject();
        },

        //copy properties to instance
        copyProp: function (opts) {
            for (var prop in opts) {
                this[prop] = opts[prop];
            }
        },

        ... 
        ...

        setCards: function () {
            //create new Cards data with default position
            this.Cards[0] = new scope.Card({ image: this.assets['cards'] });
            this.Cards[1] = new scope.Card({ image: this.assets['cards'] });
            this.Cards[2] = new scope.Card({ image: this.assets['cards'] });
        }
    };

    scope.Player = Player;
}(window));
hopper
  • 13,060
  • 7
  • 49
  • 53
PhuongTT
  • 335
  • 1
  • 8
  • 19
  • 2
    While JavaScript is an OO language it doesn't really have classes. – Jack Jul 18 '13 at 19:10
  • possible duplicate of [Javascript OOP / Classes - multiple instances share same data](http://stackoverflow.com/questions/7002946/javascript-oop-classes-multiple-instances-share-same-data) – Jack Jul 18 '13 at 19:11
  • Javascript have pseudo classes.They do what a class does but still arent class!!! – HIRA THAKUR Jul 18 '13 at 19:12
  • @MESSIAH: can i ask what js could do differently that would have you say it does have classes? – dandavis Jul 18 '13 at 19:14
  • 1
    change "Cards: []," to be "this.Cards=[]", and move it into the constructor... – dandavis Jul 18 '13 at 19:16
  • possible duplicate of [Crockford's Prototypal inheritance - Issues with nested objects](http://stackoverflow.com/questions/10131052/crockfords-prototypal-inheritance-issues-with-nested-objects) – Bergi Jul 18 '13 at 19:23
  • @dandavis: I tried to do it. It worked. But why? Can you please explain to me? Thank you. – PhuongTT Jul 19 '13 at 01:22
  • there is only one prototype object that all instances share. all properties on that prototype are also the same for all instances. properties set inside the constructor only appear in a single instance. if Obama were the constructor, lastName would be on the prototype, set to "Obama", and "Michelle" or "Barack" would be set using the this.firstName property inside the constructor. in that analogy, lastName is inherited, but firstName is one's own. – dandavis Jul 19 '13 at 01:49
  • @dandavis: I got it :D. It's about prototype chain. Thank you, dandavis. I must read more about javascript :D. – PhuongTT Jul 19 '13 at 18:01

1 Answers1

1

In Javascript functions arrays are not copied. If you reference an array it will always refer to the same array.

If you don't want to pass a reference to the same array, you will have to copy the values over to a new array. This can be simple if the array only contains strings; it can also be complex if the array contains other arrays or objects.

Make a copy of your "cards" array before passing it o your new object:

this.assets['cards'].slice(0); //Makes a copy of your array
zachzurn
  • 2,161
  • 14
  • 26
  • [Pass-by-reference](http://en.wikipedia.org/wiki/Pass-by-reference) is a different concept (for function calls), please don't use that term here. "*passing around references*" sounds better :-) – Bergi Jul 18 '13 at 19:28
  • Edited based on your advice. – zachzurn Jul 18 '13 at 19:31
  • I have already known it but i think when i create object by using new keyword, the new object and all properties will created? – PhuongTT Jul 19 '13 at 01:20
  • You mention in your question that the "cards" array is referenced by all instances. This does not mean that all card instances are the same. You can create as many new objects as you want, but if you pass them the same array, they will all reference the same array. – zachzurn Jul 22 '13 at 19:53