Simple trick to instance a class without `new`.

Adam Crockett 🌀 - Apr 22 '20 - - Dev Community

I have a case where I want a callable object, or at-least the feeling of:

{}()
{}.prop
Enter fullscreen mode Exit fullscreen mode

I am not the biggest fan of classes in the world but I have to admit it they have been getting some special treatment of late so in my case its unavoidable. private fields, class field and more. Anyway to achieve the following in a non hacky simple kind of way we need to do this:

Worth a note that this is typescript but should work in JavaScript too.

class Dog {
   static legs = 5;
   constructor() {
       console.log('woof');
   }
}

// progmatic use of `new` via .construct
// preload the first argument with the class we want to call;
// proxy the actual Reflect.construct method but point all gets and sets to the static Class constructor, in english: makes static available NOTE this does not mess with Reflect.construct
const callableObject = new Proxy(
  Reflect.construct.bind(null, Dog),
  {
    get(tar, prop, val) {
      // access static 
      return Reflect.get(Dog, prop, val);
    },
    set(tar, prop, val) {
      // access static 
      return Reflect.set(Dog, prop, val);
    },
    apply(target, thisArg, argumentsList) {
      // make the constructor work 
      return target({...argumentsList, length: argumentsList.length});
    }
  }
);
callableObject(); // calls constructor
callableObject.legs; // 5
Enter fullscreen mode Exit fullscreen mode

magic :)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player