JavaScript ES6中如何传递类作用域而非新创建对象的作用域
解决FullCalendar回调中this指向问题的优化方案
针对你遇到的eventSourceSuccess触发时this指向Calendar实例而非pop类实例的问题,有以下几种更优雅的解决方案:
方案1:使用箭头函数作为回调
箭头函数不会绑定自身的this,会继承外层作用域(即setCalendar方法中的this,也就是pop类实例)的上下文,这样在回调里调用setMinMaxSlotTime时,this自然指向pop实例:
export default class pop { calendar = null; setCalendar() { this.calendar = new Calendar(document.getElementById('calendar'), { eventSourceSuccess: (eventArray) => { this.setMinMaxSlotTime(eventArray); } }); }; setMinMaxSlotTime(eventArray) { this.calendar.setOption('slotMaxTime', maxTime + ':59:59'); } }
方案2:用bind绑定this
通过bind方法将setMinMaxSlotTime的this强制绑定为当前pop类实例,确保回调执行时上下文正确:
export default class pop { calendar = null; setCalendar() { this.calendar = new Calendar(document.getElementById('calendar'), { eventSourceSuccess: this.setMinMaxSlotTime.bind(this) }); }; setMinMaxSlotTime(eventArray) { this.calendar.setOption('slotMaxTime', maxTime + ':59:59'); } }
方案3:将方法定义为箭头函数属性
在类中直接把setMinMaxSlotTime定义为箭头函数属性,这样它的this会永久绑定到类实例,无需额外处理:
export default class pop { calendar = null; setCalendar() { this.calendar = new Calendar(document.getElementById('calendar'), { eventSourceSuccess: this.setMinMaxSlotTime }); }; setMinMaxSlotTime = (eventArray) => { this.calendar.setOption('slotMaxTime', maxTime + ':59:59'); } }
这三种方案都能避免使用that别名的临时写法,让代码更简洁且符合ES6+的规范。
内容的提问来源于stack exchange,提问作者mankowitz
相关产品推荐
相关产品推荐

