quickjs-emscripten
quickjs-emscripten copied to clipboard
Allow host functions to be treated as constructors
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
@justjake is there a workaround here? Or is this necessary to use constructors?