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.
Yes, with ES6 it is possible to subclass
Function
- however, that's not exactly nice, as the constructor expects code strings: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 newReflect.setPrototypeOf
is giving you additional freedom here.