您的位置:首页 > Web前端 > JavaScript

v8学习---使用内部字段给js添加全局变量

2013-11-10 23:09 465 查看
#include <v8.h>
#include <iostream>
using namespace v8;
void Setter(Local<String> property, Local<Value> value,
const PropertyCallbackInfo<void>& info)
{
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
void* ptr = wrap->Value();
static_cast<int*>(ptr)[0] = value->Int32Value();
}

void Getter(Local<String> property, const PropertyCallbackInfo<Value>& info)
{
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
void* ptr = wrap->Value();
info.GetReturnValue().Set(static_cast<int*>(ptr)[0]);
}

int main()
{
int age = 9527;

Isolate* isolate = Isolate::GetCurrent();
HandleScope handleScope(isolate);

Handle<ObjectTemplate> global = ObjectTemplate::New();
//所有由global这个模板产生的Object都有一个内部的字段
global->SetInternalFieldCount(1);
global->SetAccessor(String::New("age"), Getter, Setter);

Handle<Context> context = Context::New(isolate, NULL, global);
Context::Scope context_scope(context);

//global模板所产生的Object是context->Global()->GetPrototype();
//而不是context->Global(),所以context->InternalFieldCount() == 0 而
//context->Global()->GetPrototype()->InternalFieldCount() = 1
Handle<Object> global_proto = Handle<Object>::Cast(context->Global()->GetPrototype());
global_proto->SetInternalField(0, External::New(&age));

Handle<Script> script = Script::Compile(String::New("++age"));
Handle<Value> value = script->Run();
String::AsciiValue ascii(value);
printf("%s\n", *ascii);
return 0;
}

留意其中Local<External>, External::New, SetInternalFieldCount,SetInternalField,GetInternalField的用法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: