javascript - 我可以修补现有类以扩展另一个类吗?

标签 javascript

我有以下类(class),我无法更改

class Foo {
  constructor() {
    console.log('foo')
  }
}
我想使用一个函数对其进行修补,以便它扩展另一个类(调用 super() 作为它的构造函数的第一行)
function extendWithBar(TargetCtor) {
  class Bar {
    constructor() {
      console.log('bar')
    }
  }

  //... secret sauce

  // Equivalent of "Foo extends Bar"
  // can extend other classes too
  return TargetExtendingBar
}

// FooBar is a new constructor, it doesn't need to relate to Foo
// it only needs to have the same constructor
const FooBar = extendBar(Foo)

const foobar = new FooBar()
// Output:
// "bar"
// "foo"
这在 JavaScript 中是否可行,如果可以,如何实现?

最佳答案

您需要 延长 class1 到 class2 像:

class class1{
  constructor(let x , let y){
     this.x = x;
     this.y = y;
  }
}

class class2 extends class1{

 // x & y just arguments for explaining  
 constructor(let x , let y){

   // calling class1 after extends
   super(x , y);
 }
}

关于javascript - 我可以修补现有类以扩展另一个类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64710267/

相关文章:

javascript - JQuery Image Gallery - 所选图像临时更改布局

javascript - 由 requirejs 加载的 javascript 文件中的原型(prototype)函数

mobile - 在移动网站上禁用 JavaScript

javascript - 如何隔离和提取常见的 axios 调用以防止代码重复?

javascript - ng-options 的 AngularJs 条件显示

javascript - 如何验证用户输入?

javascript - 在浏览器中使用 Angular 2,无需 Reflect.js 和 zone.js

javascript - FullCalendar 日期格式

javascript - 设置与背景更改脚本一起使用的背景

javascript - jsdom 未加载或未在页面中运行外部脚本