现在的位置: 首页 > 综合 > 正文

V8 JavaScript Engine 入门指南 4.2 — 基本概念(Templates)

2012年09月21日 ⁄ 综合 ⁄ 共 1445字 ⁄ 字号 评论关闭

模板就是JavaScript 函数和对象在一个context中的蓝图。

V8有两种模板:

1.Function templates:函数模板,一个独立函数的蓝图。将一个 C++ 回调函数同一个函数模板关联起来,当 JavaScript 函数实例被调用的时候它将被调用。

2.Object templates:对象模板,每个函数模板都有一个关联的对象模板。这是用来配置通过用这个函数作为构造函数创建的对象。
你可以关联两种 C++ 回调函数到对象模板上:
1.访问器回调函数,当指定的对象属性被脚本访问的时候被调用。
2.拦截器回调函数,当任意对象属性被脚本访问的时候被调用。

一个简单的函数模板:

#include "stdafx.h"
#include
v8::Handlev8::Value> Plus(const v8::Arguments& args);//声明一个自定义函数,之后将其注册到模板中去
int _tmain(int argc, _TCHAR* argv[])
{
    // Create a stack-allocated handle scope.
   
v8::HandleScope handle_scope;

    //创建一个模板实例
   
v8::Handlev8::ObjectTemplate> global = v8::ObjectTemplate::New();
    //将我们之前实现的Plus函数模板,与JavaScript的plus函数关联起来,相当于其回调函数
   
global->Set(v8::String::New("plus"), v8::FunctionTemplate::New(Plus));

    //一个context中只能有一个模板实例
   
v8::Persistentv8::Context> context = v8::Context::New(NULL,global);

    // Enter the created context for compiling and
    // running the hello world script.
   
v8::Context::Scope context_scope(context);

    // Create a string containing the JavaScript source code.
   
v8::Handlev8::String> source = v8::String::New("plus(114,26)");
    // Compile the source code.
   
v8::Handlev8::Script> script = v8::Script::Compile(source);

    // Run the script to get the result.
   
v8::Handlev8::Value> result = script->Run();

    // Dispose the persistent context.
   
context.Dispose();

    return 0;
}
v8::Handlev8::Value> Plus(const v8::Arguments& args)
{
    unsigned int A = args[0]->Uint32Value();
    unsigned int B = args[1]->Uint32Value();
    return v8::Uint32::New(A B);
}

在plus函数里下断点,就可以发现,V8使用了自定义Plus函数去实现js代码里的plus函数

抱歉!评论已关闭.