Array property in class inheritance

10 views
Skip to first unread message

Fabio Scussel

unread,
May 21, 2013, 10:23:31 AM5/21/13
to jsclas...@googlegroups.com
Hi, jsclass team,

Please consider the follow code:

var SuperClass = new JS.Class(
{
      content: [],
      add: function(letter) { this.content.push(letter); }
});

var ChildA = new JS.Class(SuperClass,
{
      add: function(letter) { this.content.push("A" + letter); }
});

var ChildB = new JS.Class(SuperClass,
{
     add: function(letter) { this.content.push("B" + letter); }
});

var a = new ChildA();
a.add("X"); a.add("Y"); a.add("Z");
var b = new ChildB();
b.add("X"); b.add("Y"); b.add("Z");
document.write(a.content);  //EXPECTED AX,AY,AZ
document.write("<br />");
document.write(b.content); //EXPECTED BX,BY,BZ

What I'm doing wrong? 
Thanks in advance for your reply

James Coglan

unread,
May 21, 2013, 10:33:16 AM5/21/13
to jsclas...@googlegroups.com
On 21 May 2013 15:23, Fabio Scussel <fabios...@gmail.com> wrote:
var SuperClass = new JS.Class(
{
      content: [],
      add: function(letter) { this.content.push(letter); }
});

When you do this, there is only one array created and it is shared among all instances of the class via their prototype. That's why you're seeing state leak between objects. Try this instead:

var SuperClass = new JS.Class({
  initialize: function() {
    this.content = [];
  },
  add: function(letter) {
    this.content.push(letter);
  }
});

This creates a new array for every instance of the class. 

Fabio Scussel

unread,
May 21, 2013, 11:53:00 AM5/21/13
to jsclas...@googlegroups.com
Thanks a lot. Now it's working as I expect!
Reply all
Reply to author
Forward
0 new messages