Javascript - 如何将 class 工厂定义为 Extjs 样式?

Javascript - how to define class factory as Extjs style?

我正在尝试为我的项目创建一个 Extjs 风格的面向对象 UI 库,但不知道如何声明 class 结构。

我需要按以下样式创建 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 class 的行,以便我可以按照上面显示的方式创建它的实例。

您在找这样的东西吗?

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;

请注意,上述方法仅适用于不需要将参数传递给其构造函数的类。