pmed / v8pp

Bind C++ functions and classes into V8 JavaScript engine
http://pmed.github.io/v8pp/
Other
901 stars 121 forks source link

Class must always be instantiated with `new` #213

Open Deewarz opened 7 months ago

Deewarz commented 7 months ago

Summary

Currently, when you declare a class, you can call it as a function:

// C++
v8pp::class_<MyClass> MyClass_class(isolate);
MyClass_class.ctor<const FunctionCallbackInfo<Value>&>();
// JS
const test1 = new addon.MyClass(10); // right way to do
const test2 = addon.MyClass(10); // currently working, wrongly

test2 asssignation should cause an error:

Uncaught TypeError: Class constructor MyClass cannot be invoked without 'new'

attempting to "call" a class without new will result in an error.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_classes#constructing_a_class

Possible solution

You can use IsConstructCall on v8::FunctionCallbackInfo to check if the class is instanciated with new here:

https://github.com/pmed/v8pp/blob/5759d79d4ce996fc87944eccdff9ffc811c1cda0/v8pp/class.hpp#L225-L228

if(!args.IsConstructCall()) {
    //  Throw type error: Uncaught TypeError: Class constructor %s cannot be invoked without 'new'
    return;
}