Can I patch an existing class to extend another class?

Viewed 114

I have the following class and I cannot change it

class Foo {
  constructor() {
    console.log('foo')
  }
}

I would like to patch it using a function so that it extends another class (calling super() as the first line of it's constructor)

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"

Is this possible in JavaScript, if so, how?

2 Answers

you need to extends class1 to class2 like :

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);
 }
}

I was thinking about reacts Higher Order Components. ReactJS documentation says:
"Concretely, a higher-order component is a function that takes a component and returns a new component."
In your case it translates to this:
"a higher-order class is a function that takes a class and returns a new class."
EDIT: I edited so it can take a class as argument.

class Foo {
      constructor() {
        console.log('foo')
      }
    }


    function withBar(arg){
    return class extends arg{
      constructor(){
        console.log('bar')
        super()
      }
    }
    }

    const fooWithBar = withBar(Foo);
    new fooWithBar()

Related