事件处理程序通常从不同的范围(this
值)调用。如果您想要的只是处理程序中的单个值,则词法作用域是最简单的方法:
var getUrl = 'test'; // now it's just a regular variable
this.items.add(
new Ext.form.Checkbox(
{
listeners: {
check: function(checkbox, checked) {
alert(getUrl); // still available - lexical scope!
},
}
)
)
或者,如果您确实希望父对象this
在事件处理程序中可用,则可以使用Ext.Function.bind
来修改范围:
this.getUrl='test';
this.items.add(
new Ext.form.Checkbox(
{
listeners: {
check: Ext.Function.bind( function(checkbox, checked) {
alert(this.getUrl);
}, this ), // second arg tells bind what to use for 'this'
}
)
)
更新:Ext.Function.bind
是 ExtJS 4 的一个特性。如果您使用的是 ExtJS 3.x 或更低版本,则可以使用Function.createDelegate
相同的目的:
this.getUrl='test';
this.items.add(
new Ext.form.Checkbox(
{
listeners: {
check: function(checkbox, checked) {
alert(this.getUrl);
}.createDelegate(this)
}
)
)