如何将原生JS实现的进度条交互代码转换为ES6 Class类代码
正确ES6 Class改写方案
常见报错原因排查
你之前改写时报错大概率是以下几个问题:
- 事件回调函数的
this指向错误:如果直接给addEventListener传实例方法,方法内的this会指向触发事件的DOM元素而非类实例,访问实例属性/方法就会报undefined - 没有把全局状态(currentActive)、DOM元素引用挂载到类实例上,方法调用时找不到对应变量
- 类名使用了小驼峰命名,不符合ES6类的大驼峰命名规范(虽然不是语法错误,但属于不规范写法)
完整可运行代码
class ProgressStepper { // 构造函数,初始化实例 constructor() { // 挂载DOM元素到实例属性 this.progress = document.getElementById('progress') this.prev = document.getElementById('prev') this.next = document.getElementById('next') this.circles = document.querySelectorAll('.circle') // 挂载状态变量到实例属性 this.currentActive = 1 // 绑定事件回调的this指向,确保回调内this始终指向当前类实例 this.handleNextClick = this.handleNextClick.bind(this) this.handlePrevClick = this.handlePrevClick.bind(this) // 绑定事件监听 this.initEvent() // 初始化默认状态 this.update() } // 初始化事件监听 initEvent() { this.next.addEventListener('click', this.handleNextClick) this.prev.addEventListener('click', this.handlePrevClick) } // 下一步点击处理 handleNextClick() { this.currentActive++ if(this.currentActive > this.circles.length) { this.currentActive = this.circles.length } this.update() } // 上一步点击处理 handlePrevClick() { this.currentActive-- if(this.currentActive < 1) { this.currentActive = 1 } this.update() } // 状态更新方法 update() { // 更新步骤圆点状态 this.circles.forEach((circle, idx) => { if(idx < this.currentActive) { circle.classList.add('active') } else { circle.classList.remove('active') } }) const actives = document.querySelectorAll('.active') // 更新进度条宽度 this.progress.style.width = (actives.length - 1) / (this.circles.length - 1) * 100 + '%' // 更新按钮禁用状态 if(this.currentActive === 1) { this.prev.disabled = true } else if(this.currentActive === this.circles.length) { this.next.disabled = true } else { this.prev.disabled = false this.next.disabled = false } } } // 实例化进度条组件即可使用 const progressStepper = new ProgressStepper()
代码说明
- 所有原全局变量都改为类实例的属性,通过
this.xxx访问,避免全局污染 - 事件回调提前绑定this,解决this指向错乱的问题,如果你不想用bind也可以把回调写成箭头函数的类属性,比如
handleNextClick = () => {},也可以自动绑定this - 拆分了各个方法的职责,后续要扩展功能(比如增加跳转指定步骤的方法)也更方便
内容的提问来源于stack exchange,提问作者Sanju
相关产品推荐
相关产品推荐

