// v8test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <v8.h>
#pragma comment(lib, "v8_base.lib")
#pragma comment(lib, "v8_snapshot.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "winmm.lib")
using namespace v8;
int main(int argc, char* argv[]) {
// Create a stack-allocated handle scope.
HandleScope handle_scope;
// Create a new context.
Handle<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(""
"function MyObj() "
"{"
"this.myArray = [1,2,2,2,2,2]; "
"this.myDouble = Math.PI; "
"}"
"MyObj.prototype.myFunction = function(arg1,arg2)"
"{"
"return (this.myDouble + arg1 + arg2); "
"};"
"var globalObject = new MyObj();"
);
String * str = *source;
// Compile the source code.
Handle<Script> script = Script::Compile(source);
// Run the script to get the result.
Handle<Value> result = script->Run();
// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
// 通过变量名获取对象,全局变量隶属于Global()对象
Local<Object> globalObject = Local<Object>::Cast(context->Global()->Get(String::New("globalObject")));
// 获取globalObject对象的myArray属性
Handle<Array> arrayproperty = Handle<Array>::Cast(globalObject->Get(String::New("myArray")));
String::AsciiValue ascii2(arrayproperty);
printf("%s\n", *ascii2);
// 获取globalObject对象的myDouble属性
Handle<Object> doubleproperty = Handle<Object>::Cast(globalObject->Get(String::New("myDouble")));
String::AsciiValue ascii3(doubleproperty);
printf("%s\n", *ascii3);
// 获取globalObject对象的myFunction属性
Local<Function> func = Local<Function>::Cast(globalObject->Get(String::New("myFunction")));
Local<Value> argv2 [2] = {v8::Number::New(1.123123), v8::Number::New(2.234234)};
// 调用myFunction函数对象
String::AsciiValue ascii4(func->Call(globalObject, 2, argv2));
printf("%s\n", *ascii4);
// Dispose the persistent context.
(Persistent<Context>(context)).Dispose();
return 0;
}
运行结果:
function (arg1,arg2){return (this.myDouble + arg1 + arg2); }
1,2,2,2,2,2
3.141592653589793
6.498949653589793
请按任意键继续. . .