Add function template to prototype global object in v8

In V8, I would like to change the prototype of the global built-in Array object, adding some functions to it. In JavaScript, I would do this, for example:

Array.prototype.sum = function() { 
    // calculate sum of array values
};

How can I achieve the same result in C ++? I have global function templates added to the global ObjectTemplate, but I'm not sure how to do the same for a supposedly existing prototype of my own object.

+5
source share
1 answer

built-in implementation:

Handle<Value> native_example(const Arguments& a) {
   return String::New("it works");
}

for the prototype (note that for some reason we need a prototype prototype)

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); 

Using javascript:

var A = [1,2,3]
log("A.example= " + A.example)
log("A.example()= " + JSON.stringify(A.example()))
+6
source

All Articles