0
class AClass{
    someValue=0;

    value(){return this.someValue;}
}

let inst=new AClass;
if ( inst ){   // I want this to invoke inst.value() actually
    .....
}

I am looking for a way to set up a class so its instances can be invoked as a function, kind of a "default function". Is that possible in js?

Edit: An alternative:

if ( inst() ){
....
}
tru7
  • 6,348
  • 5
  • 35
  • 59
  • No. `if` does not invoke any functions, you need to call it explicitly. – Bergi Feb 19 '18 at 11:11
  • 1
    You might want to look at this [question](https://stackoverflow.com/questions/37330583/define-a-function-with-nested-functions-and-default-function) of mine, yet it is not about classes. – lolbas Feb 19 '18 at 11:13
  • https://stackoverflow.com/q/6027292/1048572 – Bergi Feb 19 '18 at 11:17
  • 1
    For `inst()` to work, your constructor must return a function. There is no way to [make an arbitrary object callable](https://stackoverflow.com/q/29680473/1048572). Returning a function either involves dirty things like [subclassing `Function`](https://stackoverflow.com/q/36871299/1048572), or simply a factory function that returns a normal [function object extended with your custom methods](https://stackoverflow.com/q/8588563/1048572) (but not using prototype inheritance). – Bergi Feb 19 '18 at 11:19

0 Answers0