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?
You can wrap the Smth instance in a Proxy with an
apply
(and maybeconstruct
) trap:I took the advice from Bergi's answer and wrapped it into an NPM module.