3

I'd like to use qx-oo (Qooxdoo) as OOP library. But I was confused by strange behaviour of field members. It's looks like that fields are shared between all objects of one class, like static members. For example, this test code

    qx.Class.define("com.BaseClass",
    {
        extend : qx.core.Object,

        members:
        {
            _children: [],

            getChildrenCount: function(){
                return this._children.length;
            },

            addChild: function(child){
                this._children.push(child);
            }
        }
    });

    var class1 = new com.BaseClass();
    var class2 = new com.BaseClass();
    showLog("class1.getChildrenCount() - " + class1.getChildrenCount())
    showLog("class2.getChildrenCount() - " + class2.getChildrenCount())
    class1.addChild("somechild");
    showLog("class1.getChildrenCount() - " + class1.getChildrenCount())
    showLog("class2.getChildrenCount() - " + class2.getChildrenCount())

will produce such log

class1.getChildrenCount() - 0
class2.getChildrenCount() - 0
class1.getChildrenCount() - 1
class2.getChildrenCount() - 1

Is there a way to accomplish this?

Or can you advice another OOP-js-lib?

Here's a full example.

blong
  • 2,815
  • 8
  • 44
  • 110
arusland
  • 115
  • 1
  • 6

1 Answers1

5

This is not a issue from qooxdoo. You should not initialize reference types on the class description. You should initialize reference types with the constructor.

There is a good article in the qooxdoo manual which explains the problem.

Here is your improved example:

    qx.Class.define("com.BaseClass",
    {
        extend : qx.core.Object,

        construct: function() {
          this._children = [];
        },

        members:
        {
            _children: null,

            getChildrenCount: function(){
                return this._children.length;
            },

            addChild: function(child){
                this._children.push(child);
            }
        }
    });