Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a function template to a global object prototype in v8

Tags:

c++

javascript

v8

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.

like image 622
shevron Avatar asked Jan 28 '13 15:01

shevron


1 Answers

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()))
like image 173
exebook Avatar answered Sep 25 '22 00:09

exebook