從V8引擎編程理解javascript執行環境


    一、V8簡介 

    google code上對它的解釋如下:

     V8 is Google's open source JavaScript engine.

    V8 is written in C++ and is used in Google Chrome, the open source browser from Google.

    V8 implements ECMAScript as specified in ECMA-262, 5th edition, and runs on Windows (XP or newer), Mac OS X (10.5 or newer), and Linux     systems that use IA-32, x64, or ARM processors.

    V8 can run standalone, or can be embedded into any C++ application.

    翻譯過來重點就是:V8引擎是一個google開發的開源javascript引擎,它是由C++編寫而成,被用在google的開源游覽器chrome上。

    

    二、Hello World

    學習任何一門語言,“hello world”往往是我們的第一步,這里也不例外,代碼如下:

#include <v8.h>

using namespace v8;

int main(int argc, char* argv[]) {

// Create a stack-allocated handle scope.
HandleScope handle_scope;

// Create a new context.
Persistent<Context> context = Context::New();

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

// Create a string containing the JavaScript source code.
Handle<String> source = String::New("'Hello' + ', World!'");

// Compile the source code.
Handle<Script> script = Script::Compile(source);

// Run the script to get the result.
Handle<Value> result = script->Run();

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

// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
return 0;
}

    具體的編譯運行方法可以參見,如下文章:http://code.google.com/intl/zh-CN/apis/v8/get_started.html

    作為一名nodejs 的開發者,我要補充一個已經安裝好node之后如何正常編譯運行該代碼,眾所周知,nodejs是以來v8引擎的,也就是說當你成功安裝好nodejs之后就已經成功安裝好v8了,具體方法:

// v8 在安裝nodejs時已經安裝完畢
// 比如在自己目錄(/home/zhujiadun.pt/)中下載了node-v0.6.10,默認安裝
// 具體:
// 1. v8.h和v8stdint.h 兩個頭文件在~/node-v0.6.10/deps/v8/include/和/usr/local/include/node/都有一份
// 2. libv8.a可以在~/node-v0.6.10/out/Release/libv8.a找到
// 運行方法
// 1. 將v8.h和v8stdint.h 拷貝到 /usr/include
// 2. 將libv8.a拷貝到這個文件目錄
// 3. g++ hello_world.cpp -o hello_world libv8.a -lpthread
// 4. ./hello_world

    

      三、執行環境講解

      js作用域的基礎知識參見:《javascript高級程序設計》讀書筆記——作用域
      強調了這么多,終於可以進入正題,通過v8的編程來體驗一把javascript執行環境相關知識。

      以上這幅圖的運行原理過程圖(圖片直接來源google的v8介紹):

    

    講解幾個概念:

    執行環境:

 Persistent<Context> context = Context::New();
 Context::Scope context_scope(context);
 context.Dispose();

    context就是這個函數的執行環境,在javascript中執行環境是一個非常重要的概念,每個函數被在調用時都會創建自己的執行環境,由它來定義代碼在哪個環境被執行。當函數執行完畢時被銷毀。

    handle:

    v8引擎如jvm一樣,會自動對不用的內存進行垃圾回收,handle就是告訴v8的垃圾回收器這個函數在堆中位置。

 

 

    文本只是對v8的相關知識進行初步的講解,v8還是比較復雜的,很多內容還在學習當中,先簡單分享些自己的學習心得吧。

    參考資料:

    http://code.google.com/intl/zh-CN/apis/v8/intro.html

    http://izs.me/v8-docs/main.html

 

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM