在v8中将函数模板添加到全局对象原型 [英] Add a function template to a global object prototype in v8

查看:384
本文介绍了在v8中将函数模板添加到全局对象原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在V8中,我想通过添加一些函数来修改全局内置数组对象的原型。在JavaScript中,我会这样做,例如:

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

如何在C ++中实现相同的结果?我有一些全局函数模板添加到全局ObjectTemplate,但我不知道如何做相同的假设现有的本机对象原型。

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.

推荐答案

原生实现:

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用法:

javascript usage:

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

这篇关于在v8中将函数模板添加到全局对象原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆