Fields are as static fields in Qooxdoo library

╄→尐↘猪︶ㄣ 提交于 2020-01-02 07:27:06

问题


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.


回答1:


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);
            }
        }
    });


来源:https://stackoverflow.com/questions/14024282/fields-are-as-static-fields-in-qooxdoo-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!