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

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.