I know creating an ObjectTemplate and we can do several things to it. But my question is not about those well-known things.
I want to know how to pass the second parameter.
As the official guide said:
Each function template has an associated object template. This is used to configure objects created with this function as their constructor.
And the second parameter of ObjectTemplate::New is a constructor typed by FunctionTemplate
.
static Local<ObjectTemplate> New(Isolate *isolate, Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
That means something like this:
void Constructor(const FunctionCallbackInfo<Value>& args)
{
// ...
}
Local<FunctionTemplate> _constructor = FunctionTemplate::New(isolate, Constructor);
Local<ObjectTemplate> tpl = ObjectTemplate::New(isolate, _constructor);
Who can give me a demo that how to implement the Constructor
function.
I tried this, but failed:
void Constructor(const FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = args.GetIsolate();
args.This()->Set(String::NewFromUtf8(isolate, "value"), Number::New(isolate, 233));
args.GetReturnValue().Set(args.This());
}
By the way, I know the use case of accessors and so on, I just want to know how to use the second parameter.
There's an example for the second ObjectTemplate::New
parameter in V8's API tests at https://chromium.googlesource.com/v8/v8/+/master/test/cctest/test-api.cc#1901:
LocalContext env;
Local<v8::FunctionTemplate> fun = v8::FunctionTemplate::New(isolate);
v8::Local<v8::String> class_name = v8_str("the_class_name");
fun->SetClassName(class_name);
Local<ObjectTemplate> templ1 = ObjectTemplate::New(isolate, fun);
templ1->Set(isolate, "x", v8_num(10));
templ1->Set(isolate, "value", v8_num(233)); // From your last snippet.
Local<v8::Object> instance1 =
templ1->NewInstance(env.local()).ToLocalChecked();
CHECK(class_name->StrictEquals(instance1->GetConstructorName()));
As you can see, there's no need to implement property creation indirectly via a FunctionTemplate
, that's what the ObjectTemplate
is for. See the "x" and "value" properties in the above example.
The quote you mentioned refers to something else. When you instantiate a function from a FunctionTemplate
, then JavaScript code can use that function as a constructor. The mentioned ObjectTemplate
can be used to configure the objects that will be created that way.