Add a function template to a global object prototype in v8

▼魔方 西西 提交于 2020-01-02 04:43:08

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/14565483/add-a-function-template-to-a-global-object-prototype-in-v8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!