引用不在作用域内的变量

refer to a variable which is not in scope

本文关键字:变量 作用域 引用      更新时间:2023-09-26

我有一个这样的结构:

{
    ....
    initComponent : function () {
        ....
        this.appCombo = Ext.create('Ext.form.field.ComboBox', {
            ....
            listeners : {
                // Use 'data' here
            }
        }
    },
    load : function () {
        var data = ....
    }
}

我希望使用我提到的数据,但' data is undefined '错误不断弹出。请告诉我如何在我指定的地方访问'data'变量。

我不确定您使用的是哪个版本。但是你应该能够添加一个配置属性——Ext会自动为这个配置生成getter和setter。在尝试在侦听器中访问数据之前,请确保load方法已经设置了数据。

{
    config: {
        data: null
    }
    ....
    initComponent : function () {
        var me = this;
        ....
        this.appCombo = Ext.create('Ext.form.field.ComboBox', {
            ....
            listeners : {
                ....me.getData(); // returns the data if it has been set already
            }
        }
    },
    load : function () {
        var me = this;
        me.setData(...);
    }
}

在对象中添加一个vars对象(不将其暴露给全局作用域),它将保存您的变量。

{
    vars : {
        data : null
    },
    initComponent : function () {
        var self = this;
        this.appCombo = Ext.create('Ext.form.field.ComboBox', {
            listeners : {
                alert(self.vars.data);
            }
        }
    },
    load : function () {
        this.vars.data = 'Hello';
        this.initComponent();
    }
}
data : null,
initComponent : function () {
    var me = this;
    this.appCombo = Ext.create('Ext.form.field.ComboBox', {
        ....
        listeners : {
            // Use 'data' here
            me.data = "FOO"
        }
    }
},
load : function () {
    this.data = ....
}