如何在Dojo中为对象分配静态数组?

时间:2012-08-19 21:10:04

标签: javascript actionscript dojo

define(["dojo/_base/declare"], function (declare) {
    // module:
    //      StyleNames
    // summary:
    //      Style element names.
    var StyleNames = declare(null, 
        {
            PROP1: "Style1",
            PROP2: "Style2"
        }
    );

    StyleNames.dataContexts = [
        StyleNames.PROP1,
        StyleNames.PROP2,
    ];

    return StyleNames;
});

var styleNames = new StyleNames();
console.log("PROP1 is defined as: ", styleNames.PROP1); // prints "Style1"
console.log("dataContexts is undefined: ", styleNames.dataContexts); // Error: styleNames.dataContexts is undefined

我的设置类似于https://stackoverflow.com/a/11329956/1610451,但在DOM中,我可以看到它被设置为具有未定义值的构造函数styleNames.constructor.dataContexts

Backstory:我正在将ActionScript代码移植到JavaScript,需要维护现有的接口。我正在移植的ActionScript代码的一个示例是:

public class StyleNames {
    public static const PROP1 : String = "Style1";
    public static const PROP2 : String = "Style2";

    public static const dataContexts : Array = [
        PROP1,
        PROP2
    ];

    public function StyleNames(){}
}

2 个答案:

答案 0 :(得分:0)

你在宣言中说得对。在我看来,这是定义静态变量最明确的方法。在您的console.log代码中,您只是没有正确引用dataContexts变量。它是静态变量,因此它不属于任何一个实例。您想以这种方式引用它:StyleNames.dataContexts

编辑:你在那里也有可能的语法错误。取出StyleNames.dataContexts声明下的第二个逗号:

StyleNames.dataContexts = [
    StyleNames.PROP1,
    StyleNames.PROP2
];

像这样访问变量:

StyleNames.dataContexts

而不是this.dataContextsinstanceRef.dataContexts

答案 1 :(得分:0)

这就是我的思维方式:

require(["dojo/_base/declare"], function(declare) {

    var StyleNames = declare(null, {

        constructor: function() {
            // a.k.a public function StyleNames(){}
        },

        // non-static properties and functions here

    });

    // static properties and functions
    StyleNames.PROP1 = "Style1";
    StyleNames.PROP2 = "Style2";

    StyleNames.dataContexts = [
        StyleNames.PROP1,
        StyleNames.PROP2
    ];

    console.log("PROP1: ", StyleNames.PROP1);
    console.log("dataContexts: ", StyleNames.dataContexts);

});​

请参阅jsFiddle的一个工作示例:http://jsfiddle.net/phusick/6nfhJ/