11

在我当前的项目中,我使用的是 ExtJs3.3。
我创建了许多具有私有变量和函数的类。例如:

MyPanel = function(config){
  config = config || {};

  var bar = 'bar';//private variable

  function getBar(){//public function
     return bar;
  }

  function foo(){
     //private function
  }

Ext.apply(config, {
  title: 'Panel',
  layout: 'border',
  id: 'myPanel',
  closable: 'true',
  items: []
});

  MyPanel.superclass.constructor.call(this, config);
};
Ext.extend(MyPanel , Ext.Panel, {
  bar: getBar
});
Ext.reg('MyPanel', MyPanel);

我知道ExtJs4中新的做事方式是使用Ext.define方法。所以我上面的代码看起来像这样:

Ext.define('MyPanel', {
  extend: 'Ext.panel.Panel',

  title: 'Panel',
  layout: 'border',
  closable: true,

  constructor: function(config) {

     this.callParent(arguments);
  },

});

所以我想知道的是如何在 ExtJs4 中定义私有变量和函数,就像我在 ExtJs3 中所做的那样?
换句话说,我知道该Ext.define方法将负责定义、扩展和注册我的新类,但是我应该在哪里声明var不是类本身的属性但类需要的 javascript 。

MyPanel = function(config){
  //In my Ext3.3 examples I was able to declare any javascript functions and vars here.
  //In what way should I accomplish this in ExtJs4.

  var store = new Ext.data.Store();

  function foo(){
  }
  MyPanel.superclass.constructor.call(this, config);
};
4

3 回答 3

8

我不喜欢像这样强制执行私有变量,但当然可以做到。只需在构造函数/initComponent 函数中为变量设置一个访问函数(闭包):

constructor: function(config) {
    var bar = 4;
    this.callParent(arguments);

    this.getBar = function() {
        return bar;
    }
},...
于 2011-05-13T07:43:24.180 回答
6

这正是配置的用途,请从 Extjs 文档中查看:

config: 配置选项及其默认值的对象列表,自动为其生成访问器方法。例如:

Ext.define('SmartPhone', {
     config: {
         hasTouchScreen: false,
         operatingSystem: 'Other',
         price: 500
     },
     constructor: function(cfg) {
         this.initConfig(cfg);
     }
});

var iPhone = new SmartPhone({
     hasTouchScreen: true,
     operatingSystem: 'iOS'
});

iPhone.getPrice(); // 500;
iPhone.getOperatingSystem(); // 'iOS'
iPhone.getHasTouchScreen(); // true;
iPhone.hasTouchScreen(); // true

这样你就可以隐藏你的实际字段并且仍然可以访问它。

于 2011-11-18T14:27:00.807 回答
5

您可以像这样创建私人成员。但是如果你为这个类创建了多个实例,它就没有用了。

Ext.define('MyPanel', function(){

    var bar = 'bar';//private variable

    function foo(){
        //private function
    };
    return {
       extend: 'Ext.panel.Panel',
       title: 'Panel',
       layout: 'border',
       closable: true,

       constructor: function(config) {

           this.callParent(arguments);
       },

       getBar: function(){//public function
           return bar;
       }

    };

});

谢谢你,

南都

于 2013-07-26T07:20:43.787 回答