Berkeley Martinez
Berkeley Martinez

Reputation: 2805

Create a class that creates Function objects as instance using es6 class syntax

Is it possible to create a class that instantiates functions with methods on it's prototype? I am trying to convert code from prototype structure to using the es6 class syntax. Here is a contrived and over simplified example of the starting point

function createFun(init) {
  function fun(newDats) {
    this.data = newDats;
    // create universe
  }
  function internalMethod() {
  }
  fun.data = init;
  fun.aMethod = function () {
    internalMethod();
  }
  assign(fun, AnExtendableClass.prototype);
  return fun;
}

// and can be used as such
fun = createFun('first');
fun('second');
fun.aMethod();
fun.methodFromExtendableClass('third')

And this is what I have tried

class Fun extend AnExtendableClass {
   constructor(init) {
     super();
     this.data = init;
     function fun(newDats) {
       this.data = newDatas;
       //create universe
     }
     assign(fun, this);
     return fun;
   }

   aMethod() {
   }
}

Unfortunately this does not work and function with no methods in return.

Upvotes: 3

Views: 346

Answers (1)

Bergi
Bergi

Reputation: 664548

Is it possible to create a class that instantiates functions with methods on it's prototype?

Yes, with ES6 it is possible to subclass Function - however, that's not exactly nice, as the constructor expects code strings:

class Fun {
    constructor() {
        super("newDats", `
            this.data = newDats;
            // create universe
        `)
    }
    data() { }
    aMethod() { }
}

let fun = new Fun;
fun(…);
fun.aMethod(…);

I am trying to convert code from prototype structure to using the es6 class syntax. Here is a contrived and over simplified example of the starting point

Don't use the class syntax for that. The new syntax is very limited, and should only be used for standard class declarations. If you do anything weird - and returning functions from the constructor, copying methods from other classes, assigning static properties and using internal methods is definitely weird in this regard - then go use the "old", explicit way. The new Reflect.setPrototypeOf is giving you additional freedom here.

Upvotes: 1

Related Questions