将Class A转为Function A时箭头函数的问题排查与处理
问题解答
你的猜测是否正确?
不正确。箭头函数本身不是导致运行异常的根源,函数式继承的代码顺序错误以及构造器指向错误才是问题核心。
问题分析
你当前的函数式写法存在两个关键错误:
- 原型方法被覆盖:你先给
A.prototype添加了init、update、destroy方法,随后又执行A.prototype = Object.create(B.prototype),这会直接替换掉之前添加的所有原型方法,导致实例调用这些方法时找不到对应函数,触发运行异常。 - 构造器指向错误:你将
A.prototype.constructor设为B,这会破坏原型链的正确性,导致instanceof等原型判断逻辑出错。
箭头函数的处理方式
在函数式继承中,箭头函数的作用和class中一致——捕获当前上下文的this(即实例对象),确保调用updateBind时this始终指向实例。只要继承写法正确,箭头函数可以正常使用。你也可以选择传统的bind写法实现相同的this绑定效果。
修正后的代码
方案1:保留箭头函数,修正继承顺序
function A(m) { B.call(this, m); } // 先完成原型继承 A.prototype = Object.create(B.prototype); A.prototype.constructor = A; // 修正构造器指向为A本身 // 再向原型添加方法 A.prototype.init = function() { this.updateBind = () => { this.update(); } window.addEventListener('resizeEnd', this.updateBind); } A.prototype.update = function() { this.scroll.update(); } A.prototype.destroy = function() { window.removeEventListener('resizeEnd', this.updateBind); this.scroll.destroy(); }
方案2:替换为bind写法(传统函数式风格)
function A(m) { B.call(this, m); } A.prototype = Object.create(B.prototype); A.prototype.constructor = A; A.prototype.init = function() { // 使用bind将update的this绑定到实例 this.updateBind = this.update.bind(this); window.addEventListener('resizeEnd', this.updateBind); } A.prototype.update = function() { this.scroll.update(); } A.prototype.destroy = function() { window.removeEventListener('resizeEnd', this.updateBind); this.scroll.destroy(); }
说明
两种方案都能解决问题:
- 箭头函数写法更简洁,自动捕获实例
this; bind写法是函数式继承中绑定this的传统方式,兼容性更广(不过现代环境下两者差异不大)。
内容的提问来源于stack exchange,提问作者goodcontext
相关产品推荐
相关产品推荐

