如何正确将 ES6 类转换为传统函数构造器并保持原型链继承

8次阅读

如何正确将 ES6 类转换为传统函数构造器并保持原型链继承

es6 类改为函数构造器时,若在设置原型链后又定义方法,会导致方法被覆盖为 undefined;关键在于先建立 `a.prototype = Object.create(b.prototype)`,再添加实例方法,而非反之。

在将 class A extends B 迁移为函数构造器 function A(m) 的过程中,核心问题并非箭头函数 this.updateBind = () => { this.update(); } 本身——它在函数构造器中完全合法且能正确绑定 this(因为箭头函数继承外层作用域的 this,而此处外层是实例上下文)。真正导致 init()、update()、destroy() 等方法调用失败的根本原因,是原型链初始化顺序错误

原始错误代码中:

A.prototype.init = function() { /* ... */ }; A.prototype.update = function() { /* ... */ }; // ... 其他方法定义  A.prototype = Object.create(B.prototype); // ❌ 覆盖整个 prototype! A.prototype.constructor = B;

该写法先向 A.prototype 添加了若干方法,但紧接着 A.prototype = Object.create(B.prototype) 重新赋值了整个原型对象,导致之前定义的所有方法(init、update 等)全部丢失,变为 undefined。因此即使 this.updateBind 正确创建,this.update() 在执行时也会抛出 TypeError: this.update is not a function。

✅ 正确做法:必须先建立继承关系,再扩展方法

function A(m) {   B.call(this, m); // 手动调用父构造器 }  // ✅ 关键:先设置原型链继承 A.prototype = Object.create(B.prototype); A.prototype.constructor = A; // ⚠️ 注意:constructor 应指向 A,而非 B!  // ✅ 再定义实例方法 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(); };

? 补充说明与注意事项:

  • A.prototype.constructor = A 是良好实践,确保 new A() instanceof A 正确返回 true;若设为 B,则 instanceof 检查会失真;
  • 箭头函数 this.updateBind 在函数构造器中无需特殊处理——只要 this 是实例(即通过 new A() 创建),其内部 this.update() 就能正常访问到 A.prototype.update;
  • 若需兼容更老环境或避免 this 绑定隐患,也可改用 bind 显式绑定(但非必需):
    this.updateBind = this.update.bind(this);
  • 强烈建议在 update 和 destroy 中加入空值检查(如 this.scroll?.update()),防止 scroll 未初始化时崩溃;
  • 最终验证方式:实例化后检查方法是否存在:
    const instance = new A({/* config */}); console.log(typeof instance.init, typeof instance.update); // 应输出 "function function"

综上,迁移类到函数构造器的核心原则是:继承先行,扩展在后;箭头函数可用,但原型赋值时机决定一切。

text=ZqhQzanResources