字段在Qooxdoo库中作为静态字段 [英] Fields are as static fields in Qooxdoo library

查看:110
本文介绍了字段在Qooxdoo库中作为静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用qx-oo(Qooxdoo)作为OOP库。但我对场外成员的奇怪行为感到困惑。看起来这些字段在一个类的所有对象之间共享,就像静态成员一样。例如,此测试代码

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())

将生成此类日志

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

有没有办法实现这个目标?

Is there a way to accomplish this?

或者你能建议另一个OOP吗? -js-lib?

这是一个完整的示例

推荐答案

这不是qooxdoo的问题。您不应该在类描述上初始化引用类型。你应该用构造函数初始化引用类型。

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.

qooxdoo中有一篇好文章手册解释了这个问题。

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

这是你的改进示例

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

这篇关于字段在Qooxdoo库中作为静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆