5

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.

shevron
  • 3,463
  • 2
  • 23
  • 35

1 Answers1

5

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()))
exebook
  • 32,014
  • 33
  • 141
  • 226