Create a class that creates Function objects as in

2019-07-21 23:27发布

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.

1条回答
Animai°情兽
2楼-- · 2019-07-21 23:51

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.

查看更多
登录 后发表回答