Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExtJs inheritance behaviour

Can someone please explain this behavior to me. Lets declare a class:

Ext.define('baseClass',{
    a:null,
    ar:[],

    add:function(v) {
        this.ar.push(v);
    },
    sayAr:function() {
        console.log(this.ar);
    },

    setA:function(v) {
        this.a= v;
    },
    sayA:function() {
        console.log(this.a);
    }
});

Now I create two objects

var a = Ext.create('baseClass');
var b = Ext.create('baseClass');

Test the property

a.setA(1);
b.setA(2);

a.sayA();
b.sayA();

This outputs

1
2

Everything is OK, but

a.add(1);
b.add(2);

a.sayAr();
b.sayAr();

We get

[1,2]
[1,2]

This I don't understand. Why does it use separate "a" properties but one "ar" array for both objects. "ar" is not declared as static! I don't get it at all.

like image 259
mik Avatar asked Aug 15 '12 07:08

mik


2 Answers

When you put something in the class declaration, it means it gets pushed onto the object prototype (read: it gets shared across all instances). It's not really a problem for strings/numbers/bools, but for objects and arrays you'll see this behaviour come in to effect.

If you want to have an array/object per instance, then you need to explicitly add it in the instance:

Ext.define('baseClass',{
    a:null,

    constructor: function(){
        this.ar = [];
    }

    add:function(v) {
        this.ar.push(v);
    },
    sayAr:function() {
        console.log(this.ar);
    },

    setA:function(v) {
        this.a= v;
    },
    sayA:function() {
        console.log(this.a);
    }
});
like image 134
Evan Trimboli Avatar answered Sep 28 '22 18:09

Evan Trimboli


That's because of this bit here:

Ext.define('baseClass',{
   a:null,
   ar:[], <--------------------------- you're instantiating an array object!

To make it clearer, the above code is equivalent to:

Ext.define('baseClass',{
   a:null,
   ar:new Array(),

So both objects share the same array because the object constructor only copies the reference to the array not the full array object.

Not sure how Ext.js handles constructors/initializers but you need to create the array during object construction not when you declare it....

OK, Googling gave me this:

Ext.define('baseClass',{
    constructor: function () {
        this.ar = [];
    },

That should solve your problem.

like image 20
slebetman Avatar answered Sep 28 '22 18:09

slebetman