谁能告诉我为什么我一直得到一个方法buildItems没有定义在下面的代码?我是不是漏掉了什么重要的东西?
Ext.define('MyApp.view.Viewport', {
extend: 'Ext.container.Viewport',
requires: [
'Ext.layout.container.Border'
],
layout : 'border',
items : [this.buildItems()],
buildItems : function() {
return { region:'center',xtype:'panel'}
}
});
buildItems方法没有理由成为一个公共方法,我只是先尝试这种方式。我现在是这样做的:
(function() {
function buildItems () {
return [
{
region : 'center',
xtype : 'panel',
}, {
region : 'west',
xtype : 'panel',
width : 225
},{
region : 'south',
xtype : 'panel',
height : 50
},{
region : 'north',
xtype : 'panel',
height : 50
}
]
}
return Ext.define('MyApp.view.Viewport', {
extend: 'Ext.container.Viewport',
requires: [
'Ext.layout.container.Border'
],
layout : 'border',
items : buildItems()
});
})();
这是不是太夸张了?
thx
问题是:在执行
这一行时items : [this.buildItems()],
作用域是全局对象,即this
求值为window
。无论如何,您不应该将items
放入类中,因为实例可能会修改item
的项,因此正确的方法是
initComponent: function () {
this.items = this.buildItems(); // now, "this" is the current component instance
// superclass.initComponent...
}
编辑:作为问题第二部分的回答
这个问题已经讨论过无数次了,将helper函数设为私有并没有什么错。我个人倾向于将方法保持为公共的,因为这样可以提高代码的可读性。通常我使用文档注释(@private
)作为标记,并且非常简单地避免调用所谓的私有方法。我认为这没什么大不了的,因为我不是在为第三方开发人员构建库或任何可重用的东西。
这是因为函数是在另一个函数中定义的,并且视口将在这个自执行函数之外访问。所以,把这个buildItems()放在自执行函数之外,并尝试相同的