In V8, I would like to modify the prototype of the global built-in Array object, by adding some functions to it. In JavaScript, I would do it like this, for example:
Array.prototype.sum = function() {
// calculate sum of array values
};
How can I achieve the same result in C++? I have some global function templates added to the global ObjectTemplate, but I am not sure how to do the same for a supposedly existing native object prototype.
native implementation:
Handle<Value> native_example(const Arguments& a) {
return String::New("it works");
}
assignment to prototype (notice we need a prototype of a prototype for some reason)
Handle<Function> F = Handle<Function>::Cast(context->Global()->Get(String::New("Array")));
Handle<Object> P = Handle<Object>::Cast (F->GetPrototype());
P = Handle<Object>::Cast(P->GetPrototype());
P->Set(String::New("example"), FunctionTemplate::New(native_example)->GetFunction(), None);
javascript usage:
var A = [1,2,3]
log("A.example= " + A.example)
log("A.example()= " + JSON.stringify(A.example()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With