我正在使用 Ext JS4 开发一个项目。在我们的一些类中,我们在 initComponent 函数中声明函数,然后可以将其设置为控件的处理程序。我将在下面包含一个示例。忽略类中的大部分内容,关键细节是处理程序在 initComponent 中声明并设置为按钮的处理程序这一事实。
现在,这实际上是有效的——这里的问题是为什么它有效。我对 JavaScript 相当陌生,但我认为函数中声明的任何变量或函数在函数完成后都会被销毁。这是不正确的吗?我很欣赏这可能有更好的编码风格,但在考虑更改大量类之前,我真的很想弄清楚这一点。课程如下......一些评论确定了关键领域。
Ext.onReady(function () {
Ext.application({
name: 'Form2',
thisForm: {},
launch: function() {
thisForm = Ext.create('Form2', {});
}
});
});
Ext.define('Form2', {
extend: 'Ext.form.Panel',
layout:'border',
config: {
controlManager: {},
formVariables: {},
dataHelper: {}
},
constructor: function () {
var me = this;
...
...
// Initialize the form - I know, this might not be the be best coding style here.
me.initComponent();
},
initComponent: function() {
Ext.QuickTips.init();
var ButtonControl1 = this.controlManager.createButton('ButtonControl1');
var ButtonControl2 = this.controlManager.createButton('ButtonControl2');
...
...
// Handler for Btton1 - **I'm not using the var keyword in this declaration**
function Handler1() {
alert('This Works!');
};
// Handler for Btton2 - **I'm using the var keyword in this example**
var Handler2 = function () {
alert('This Works also!');
};
// THIS IS THE KEY PART OF THIS QUESTION - even though the handler functions are declared
// locally (above), clicking the buttons will still execute these. Do the functions
// still exist by chance, and will be garbage collected at some later time, or are they
// actually quaranteed to be there. I'm confused!
ButtonControl1.onClickEventHandler = function () {Handler1();};
ButtonControl2.onClickEventHandler = function () {Handler2();};
// Don't need to worry about this part.
Ext.create('Ext.container.Viewport', {
layout:'border',
style: { position:'relative' },
defaults: {
collapsible: true,
split: true,
bodyStyle: 'padding:0px'
},
items: [
{
collapsible: false,
split: false,
region: 'north',
height: 50,
margins: '0 2 0 2',
bbar: '',
items: [ ]
},
{
collapsible: false,
split: false,
region:'west',
margins: '0 0 0 0',
cmargins: '0 2 0 2',
width: 0,
lbar: [ ]
},
{
collapsible: false,
region:'center',
margins: '0 2 0 2',
layout: {
align: 'stretch',
type: 'hbox'
},
items: [
{
xtype: 'form',
fileUpload: true,
layout: {
align: 'stretch',
type: 'vbox'
},
flex: 1,
items: [
{
xtype: 'container',
height: 550,
layout: {
align: 'stretch',
type: 'hbox'
},
items: [
{
xtype: 'container',
width: 570,
layout: 'vbox',
padding: '5 0 0 0',
style:'background-color:rgb(255, 255, 255);',
items: [
ButtonControl1, ButtonControl2
]
}
]
}
]
}
]
}
]
});
}
});