You can use built-in Function constructor: v8::Local<v8::Function> MkFunction(v8::Handle<v8::String> body) { v8::HandleScope scope;
// Get global object v8::Local<v8::Object> global = v8::Context::GetCurrent()->Global(); // Get built-in Function constructor (see ECMA-262 5th edition 15.3.2) v8::Local<v8::Function> function_ctor = v8::Local<v8::Function>::Cast(global->Get(v8::String::New("Function"))); // Invoke Function constructor to create function with the given body and no arguments v8::Handle<v8::Value> argv[1] = { body }; v8::Local<v8::Object> function = function_ctor->NewInstance(1, argv); return scope.Close(v8::Local<v8::Function>::Cast(function)); } -- Vyacheslav Egorov, Software Engineer, V8 Team. Google Denmark ApS. On Thu, Mar 10, 2011 at 5:40 PM, Vasily <vasily.stepa...@gmail.com> wrote: > Consider a v8::String variable containing some js code. > For instance: > v8::Local<v8::String> source = v8::String::New("this.foo();"); > > I want to evaluate js code with my explicitly defined 'this' keyword. > First of all I found v8::Function::Call() method. Where I can pass > 'this' object with recv argument (sic). > > My idea was to create v8::Function: > v8::Local<v8::FunctionTemplate> templ = > v8::FunctionTemplate::New(eval, source); > v8::Local<v8::Function> function = templ->GetFunction(); > > where eval is: > v8::Handle<v8::Value> eval(const v8::Arguments &args) { > v8::Handle<v8::String> source = > v8::Handle<v8::String>::Cast(args.Data()); > // I'm not talking about performance here. It's not a real life ;) > v8::Local<v8::Script> script = v8::Script::Compile(source); > script->Run(); > return v8::Undefined(); > } > > and call this function like this: > function->Call(myObj, 0, NULL); > > But what I found is that inside eval, args.This() points to my object > (and that is good)... unfortunately inside script->Run() in expression > "this.foo()", 'this' means Global object of a current context. And > that is probably what expected by v8 developers... but definitely not > good for me :) > > My dirty solution is to build "function() { " + source + "}" string, > Compile, Run and Cast the result to v8::Function. > > Is there any clever solution? > > Thanks. > > -- > v8-users mailing list > v8-users@googlegroups.com > http://groups.google.com/group/v8-users > -- v8-users mailing list v8-users@googlegroups.com http://groups.google.com/group/v8-users