MyObject::MyObject(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); if (args.IsConstructCall()) { // Called as constructor: `new MyObject(...)` } else { // Called as plain function `MyObject(...)`, throw an error isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Cannot call constructor as function"))); return; } // Rest of the constructor code }
class A { public: A(int value) : value_(value) {} static A Create(int value) { A a(value); a.is_construct_call_ = true; return a; } bool IsConstructCall() const { return is_construct_call_; } private: int value_; bool is_construct_call_ = false; };In this example, the IsConstructCall method is defined on class A which returns the value of the `is_construct_call_` member variable. The `Create` method sets this variable to true to indicate that it is a constructor call. This way, the constructor can be used as a factory function and the returned object can be checked if it was created using a constructor call or not. Package/library: V8 JavaScript engine, Boost library.