模板就是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函數