quickjs-emscripten icon indicating copy to clipboard operation
quickjs-emscripten copied to clipboard

Allow host functions to be treated as constructors

Open ObsidianX opened this issue 1 year ago • 1 comments

When creating new functions on the host side, it's not currently possible to create a constructor that can be called with new from within the VM. The only thing that needs to change to enable this is the function type used when creating the function with JS_NewCFunctionMagic.

Example:

Host:

vm.newFunction('Cat', () => {
  const cat = vm.newObject();
  vm.setProp(cat, 'breed', 'calico');
  return cat;
});

Script:

const cat = new Cat();
console.log(cat.breed);
// "calico"

Without this change the error "not a constructor" is thrown instead.

Creating synthetic constructors is also supported in the qjs REPL:

qjs > function Cat() { return { breed: 'calico' }; }
qjs > const cat = new Cat()
qjs > console.log(cat.breed)
calico

ObsidianX avatar Jan 28 '25 01:01 ObsidianX

@justjake is there a workaround here? Or is this necessary to use constructors?

kylecarbs avatar Sep 03 '25 21:09 kylecarbs