繁体   English   中英

私有函数和变量ExtJs4?

[英]Private functions and Variables ExtJs4?

在我目前的项目中,我使用的是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方法将负责定义,扩展和注册我的新类,但是我应该在哪里声明javascript var ,它们不是类本身的属性,而是类所需要的。

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);
};

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

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

    this.getBar = function() {
        return bar;
    }
},...

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

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

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

这样你就可以隐藏你的实际领域并仍然可以访问它。

您可以像这样创建私人成员。 但是,如果您为此类创建多个实例,则无效。

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;
       }

    };

});

谢谢,

南都

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM