ES6 allows to extend special objects. So it's possible to inherit from the function. Such object can be called as a function, but how can I implement the logic for such call?
class Smth extends Function {
constructor (x) {
// What should be done here
super();
}
}
(new Smth(256))() // to get 256 at this call?
Any method of class gets reference to the class instance via this. But when it is called as a function, this refers to window. How can I get the reference to the class instance when it is called as a function?
The
supercall will invoke theFunctionconstructor, which expects a code string. If you want to access your instance data, you could just hardcode it:but that's not really satisfying. We want to use a closure.
Having the returned function be a closure that can access your instance variables is possible, but not easy. The good thing is that you don't have to call
superif you don't want to - you still canreturnarbitrary objects from your ES6 class constructors. In this case, we'd doBut we can do even better, and abstract this thing out of
Smth:Admittedly, this creates an additional level of indirection in the inheritance chain, but that's not necessarily a bad thing (you can extend it instead of the native
Function). If you want to avoid it, usebut notice that
Smthwill not dynamically inherit staticFunctionproperties.