class Point {
public:
int x;
int y;
int sum() { return x + y; }
};
void PointConstructor(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (!args.IsConstructCall()) {
isolate->ThrowException(String::NewFromUtf8(isolate, "Can only be called as constructor."));
return;
}
Point* p = new Point();
p->x = args[0]->IntegerValue();
p->y = args[1]->IntegerValue();
args.This()->SetInternalField(0, External::New(isolate, p));
}
void PointSum(const FunctionCallbackInfo<Value>& args) {
Local<External> field = Local<External>::Cast(args.This()->GetInternalField(0));
Point* p = static_cast<Point*>(field->Value());
args.GetReturnValue().Set(p->sum());
}
int main(int argc, char* argv[]) {
// ... initialize V8
// Create the global object with print function for test
Local<ObjectTemplate> global = ObjectTemplate::New(isolate);
global->Set(String::NewFromUtf8(isolate, "print"), FunctionTemplate::New(isolate, PrintCallback));
// Create the point constructor template
Local<FunctionTemplate> point_constructor = FunctionTemplate::New(isolate, PointConstructor);
Local<ObjectTemplate> point_template = point_constructor->InstanceTemplate();
point_template->SetInternalFieldCount(1);
point_template->Set(String::NewFromUtf8(isolate, "sum"), FunctionTemplate::New(isolate, PointSum));
point_template->SetHandler(NamedPropertyHandlerConfiguration(NamedGet));
// Add the constructor to the global object as the type
global->Set(String::NewFromUtf8(isolate, "Point"), point_constructor);
// ... compile and run code.
}class MyPoint extends Point {
sum() {
return 25;
}
}
var p = new MyPoint(2, 3);
print(p.sum()) // Prints 5, using the native function