SetCallAsFunctionHandler doesn't work with the global object?

61 views
Skip to first unread message

Danny Dorfman

unread,
Apr 2, 2015, 4:43:08 AM4/2/15
to v8-u...@googlegroups.com
Hello there,

I am trying to implement a functionality that will enable the global object to be called as if it were a function.
I know how to set it up for regular objects, but I can't seem to work it out for global. Here is a sample program:

#include <v8.h>
#include <iostream>

void RunIt(v8::Isolate *isolate, const char *script_text)
{
  v8::HandleScope handle_scope(isolate);
  std::cout << "/" << script_text << "/ <==" << std::endl;
  v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate,script_text);
  v8::Local<v8::Script> script = v8::Script::Compile(source);
  v8::Local<v8::Value> result = script->Run();
  std::cout << "/" << script_text << "/ ==> " << *v8::String::Utf8Value(result) << std::endl;
}

void CallParenthesis(const v8::FunctionCallbackInfo<v8::Value>& args)
{
  v8::EscapableHandleScope handle_scope(args.GetIsolate());
  std::cout << "CALL PARENTHESIS runs (for " << *v8::String::Utf8Value(args.This()) << ")" << std::endl;
  v8::Local<v8::Value> retval = v8::String::NewFromUtf8(args.GetIsolate(), "hello");
  args.GetReturnValue().Set(handle_scope.Escape(retval));
}

int main(int argc, char* argv[])
{
  v8::V8::Initialize();
  v8::Isolate* isolate = v8::Isolate::New();
  v8::Isolate::Scope isolate_scope(isolate);
  v8::HandleScope handle_scope(isolate);

  // global template
  v8::Handle<v8::ObjectTemplate> globalTemplate = v8::ObjectTemplate::New();
  globalTemplate->SetCallAsFunctionHandler(CallParenthesis);
  v8::Handle<v8::Context> context = v8::Context::New(isolate,NULL,globalTemplate);
  v8::Context::Scope context_scope(context);

  // specific template
  v8::Local<v8::ObjectTemplate> specificTemplate = v8::ObjectTemplate::New();
  specificTemplate->SetCallAsFunctionHandler(CallParenthesis);
  v8::Handle<v8::Object> specificObj = specificTemplate->NewInstance();
  context->Global()->Set(v8::String::NewFromUtf8(isolate,"obj"), specificObj);

  // test
  RunIt(isolate,"a = obj();");
  std::cout << std::endl;
  RunIt(isolate,"window = this; b = window();");
  std::cout << std::endl;

  return 0;
}

What I get is:

a = obj();/ <==
CALL PARENTHESIS runs (for [object Object])
/a = obj();/ ==> hello

/window = this; b = window();/ <==
<unknown>:19: Uncaught TypeError: object is not a function
/window = this; b = window();/ ==> 

Is there any way to make it work?

Regards,
Danny
Reply all
Reply to author
Forward
0 new messages