我试图使用来模仿Java与Java的以下行为mootools/Dojo
。需要使用类静态变量值初始化的实例变量。
Class xyz {
public static static_constants {
TEST_CONST1 : "abc";
}
private a = static_constants.TEST_CONST1;
}
我可以按照下面的方式来做,但是com.example.test.static_constants.TEST_CONST1
由于我们已经覆盖了,因此不再存在com.example.test
。但是,如果com.example.test.static_constants.TEST_CONST1
之前未定义,则类中的赋值操作将失败。
com.example.test.static_constants.TEST_CONST1 = "abc";
var com.example.test = new Class ({
a : com.example.test.static_constants.TEST_CONST1
});
两种可行的解决方法:
var com.example.test = new Class ({
static_constants : {
TEST_CONST1 : "abc"
},
a : this.static_constants.TEST_CONST1
});
com.example.test.static_constants.TEST_CONST1 = "abc";
com.example.test.static_constants.TEST_CONST1 = "abc";
var com.example.test = new Class ({
a : com.example.test.static_constants.TEST_CONST1
});
com.example.test.static_constants.TEST_CONST1 = "abc";
我想念什么?这两种方式对我来说似乎都不干净。必须有一个更干净的方法来执行此操作(不使用扩展等-这将进一步破坏类)。
我可以在这儿打扰并阻止您。
JavaScript不是JAVA。现在不需要使用JAVA的事实并不意味着您需要将与名称空间,静态变量和模式相关联的废话转移到JavaScript。在做事时,JavaScript有不同的模式。
无论如何,由于您没有问过在MooTools中组织东西和类的最佳模式是什么,而您只是想知道如何变异和扩展现有对象,因此可以做一个小工厂:
var com = {
example: {
test: {
static_constants: {
TEST_CONST1: "abc"
}
}
}
};
Class.extend({
fromExisting: function(namespace, constructorObject){
return Object.append(new this(constructorObject), namespace);
}
});
// this is non-DRY. It kind of is Object.merge()
com.example.test = Class.fromExisting(com.example.test, {
a: com.example.test.static_constants.TEST_CONST1,
initialize: function(){
console.warn(this.a);
},
getStatic: function(what){
return com.example.test.static_constants[what];
}
});
var t = new com.example.test();
console.log(Object.getOwnPropertyNames(t)); // no static_constants
console.log(t.a);
console.log(com.example.test.static_constants);
com.example.test.static_constants.TEST_CONST1 = 'bbb';
console.log(t.a);
console.log(t.getStatic('TEST_CONST1'));
Class.fromExisting
会接受一些对象,它将对象的属性与类构造函数对象合并(但是是静态的,而不是在原型上)-但它无法使在构造函数中扩展的obj发生突变(无法想到为什么现在但是在星期六)夜晚)。
您真的应该只实现更明智的模块命名方法/命名空间-例如在AMD中并constants
在单独的配置对象上使用。不需要混合使用两个名称空间,或者实际上,使用AMD时完全不需要名称空间(尽管可以命名模块)。
请不要使用此工厂模式,仅显示扩展类型等时Mootools的灵活性。
相反,您可以简单地-如前所述-只是 Object.merge()
com.example.test = Object.merge(new Class({
a: com.example.test.static_constants.TEST_CONST1,
initialize: function(){
console.warn(this.a);
},
getStatic: function(what){
return com.example.test.static_constants[what];
}
}), com.example.test);
由于您正在使用一些狡猾的命名空间,因此您想查看使用get / set进行扩展的Object Type(而不是Object的原型),它可以深入工作,Daniel Buchner尝试着将其降落,但遭到了拒绝。
https://github.com/mootools/mootools-core/pull/2191/files
这些可以消除从点缀字符串创建更深的名称空间的痛苦。现在玩得开心。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句