javascriptclassextending-classes

Define a class that extends Function


I'm trying to create a class that extends Function.

var MyClass = class MyClass extends Function {
  constructor(func, /*some other things*/) {
    //this is not defined in extended classes for some reason
    var newThis = func;
    //assign other stuff to newThis
    return newThis;
  }

  //methods

}

At first I thought this would work but an instanceof check revealed that the object created was just a regular function without any of my methods or properties. So then I realised that I need to use the super keyword to construct a Function.

var newThis = super(func.toString().split('(')[1].split(')')[0].split(','),
                    func.toString().split('{')[1].split('}')[0])

This works but it doesn't comply with the content security policy (something like that) which means that it won't work in chrome apps.


Solution

  • I'm not 100% what you're trying to do, but in order to correctly extend a class in ES6 you must called super() before you do anything.

    class Foo extends Function {
    
      constructor(){
        super();
        this.x = 'foo';
      }
    
    }
    
    let test= new Foo();
    console.log(test.x); // 'foo'
    

    You can try it out on the babel REPL here