ExtJS单例类创建与调用问题:获取值返回undefined求指导
问题分析与解决
核心问题1:调用方式错误
你定义的单例类是MyApp.PdfDrawRect,但调用时使用了MyApp.getZoomValue()——MyApp命名空间下并没有这个方法,所以必然返回undefined。正确的调用方式应为:
MyApp.PdfDrawRect.getZoomValue()
核心问题2:自定义setter方法实现错误
你的setZoomValue方法直接给MyApp.PdfDrawRect.zoomValue赋值,但ExtJS通过initConfig初始化config属性后,属性是绑定在实例上的;且单例的this指向实例本身,直接访问类的属性会破坏框架的属性管理逻辑。
修复后的代码方案
方案1:使用ExtJS自动生成的setter/getter(推荐)
ExtJS会为config中的属性自动生成标准的setter和getter方法,无需自定义,直接使用即可:
Ext.define('MyApp.PdfDrawRect', { singleton: true, config: { zoomValue: 1 }, constructor: function (config) { this.initConfig(config); return this; } });
调用示例:
// 设置缩放值 MyApp.PdfDrawRect.setZoomValue(2); // 获取缩放值 console.log(MyApp.PdfDrawRect.getZoomValue()); // 输出2
方案2:保留自定义方法的正确写法
如果需要自定义方法逻辑,需确保操作实例属性而非直接访问类:
Ext.define('MyApp.PdfDrawRect', { singleton: true, config: { zoomValue: 1 }, constructor: function (config) { this.initConfig(config); return this; }, setZoomValue: function (value) { console.log('setZoomValue'); // 操作实例属性,或调用框架set方法保证逻辑完整 this.set('zoomValue', value); }, getZoomValue: function () { console.log('getZoomValue'); return this.get('zoomValue'); } });
调用示例:
MyApp.PdfDrawRect.setZoomValue(1.5); console.log(MyApp.PdfDrawRect.getZoomValue()); // 输出1.5
内容的提问来源于stack exchange,提问作者johnDoe
相关产品推荐
相关产品推荐

