auto platform = platform::NewDefaultPlatform();
V8::InitializePlatform(platform.get());
V8::Initialize();
std::string flags = "--expose_gc --jitless";
V8::SetFlagsFromString(flags.c_str(), flags.size());
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = ArrayBuffer::Allocator::NewDefaultAllocator();
Isolate* isolate = Isolate::New(create_params);
{
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<FunctionTemplate> myClassTemplate = FunctionTemplate::New(isolate);
Local<FunctionTemplate> myInstanceMethodTemplate = FunctionTemplate::New(isolate);
myClassTemplate->InstanceTemplate()->Set(v8::String::NewFromUtf8(isolate, "myInstanceMethod", v8::NewStringType::kNormal).ToLocalChecked(), myInstanceMethodTemplate);
Local<ObjectTemplate> globalTemplate = ObjectTemplate::New(isolate);
globalTemplate->Set(v8::String::NewFromUtf8(isolate, "MyClass", v8::NewStringType::kNormal).ToLocalChecked(), myClassTemplate);
Local<v8::Context> context = v8::Context::New(isolate, nullptr, globalTemplate);
Context::Scope context_scope(context);
{
Local<v8::Function> myClassCtor = myClassTemplate->GetFunction(context).ToLocalChecked();
Local<v8::Function> myStaticMethod = v8::Function::New(context, nullptr).ToLocalChecked();
assert(myClassCtor->Set(context, v8::String::NewFromUtf8(isolate, "myStaticMethod", v8::NewStringType::kNormal).ToLocalChecked(), myStaticMethod).FromMaybe(false));
std::string src = R"(
// I want to intercept setting this static method and raise some C++ callback when this code is executed
MyClass.myStaticMethod = () => { };
// I want to intercept setting this instance method and raise some C++ callback when this code is executed
MyClass.prototype.myInstanceMethod = () => { };
)";
Local<v8::String> source = v8::String::NewFromUtf8(isolate, src.c_str(), v8::NewStringType::kNormal).ToLocalChecked();
Local<Script> script = Script::Compile(context, source).ToLocalChecked();
Local<Value> result = script->Run(context).ToLocalChecked();
assert(!result.IsEmpty());
}
}
isolate->Dispose();
V8::Dispose();
V8::ShutdownPlatform();
delete create_params.array_buffer_allocator;
myClassTemplate->InstanceTemplate()->SetHandler(NamedPropertyHandlerConfiguration(nullptr, [](Local<Name> property, Local<Value> value, const PropertyCallbackInfo<Value>& info) {
printf("ok");
}));
myClassTemplate->PrototypeTemplate()->SetHandler(NamedPropertyHandlerConfiguration(nullptr, [](Local<Name> property, Local<Value> value, const PropertyCallbackInfo<Value>& info) {
printf("This will be called when setting the instance method on the prototype");
}));