我正在尝试为我的项目创建一个 Extjs
风格的面向对象的 UI 库,但不知道如何声明类结构。
我需要按以下样式创建 UI 对象的实例:
var Corejs = {}; // the top object of my library,
// var Corejs = function() {}; // or maybe should put it this way,
window.$C = Corejs;
// here should define a `Panel` class, that belong to Corejs in some format,
var aPanel = $C.create('Corejs.Panel', {width: '200px', height:'100px'});
任何人都可以帮我添加定义 Panel
类的行,以便我可以按照上面显示的方式创建其实例。
最佳答案
您正在寻找这样的东西吗?
var Corejs = {
classes: {}, // Class name to constructor map
create: function(name, properties) {
try {
var clazz = Corejs.classes[name];
var instance = new clazz();
for (var property in properties) {
instance[property] = properties[property];
}
return instance;
} catch (error) {
// Handle this however you want
}
}
};
要使上述方法发挥作用,您的 Corejs 组件只需向共享 Corejs 库注册自己,如下所示:
var Panel = function() { /* ... */ };
Corejs.classes['Panel'] = Panel;
请注意,上述方法仅适用于不需要将参数传递给其构造函数的类。
关于Javascript - 如何将类工厂定义为 Extjs 风格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29184633/