I'm using libv8 (libnode in Ubuntu) where I define my own function "test()" which can be called from javascript. This function returns object {code: 3.14, message: "Some message"}:
void test(const v8::FunctionCallbackInfo < v8::Value > &args) {
// This functions returns {code: 3.14, message: "Some message"}
printf("This is test()\n");
v8::Isolate *iso = args.GetIsolate();
v8::HandleScope handle_scope(iso);
// Create object with 2 properties
v8::Handle<v8::Object> o = v8::Object::New(iso);
o->Set(v8::String::NewFromUtf8(iso, "code"), v8::Number::New(iso, 3.14));
o->Set(v8::String::NewFromUtf8(iso, "message"), v8::String::NewFromUtf8(iso, "Some message"));
// Return object
args.GetReturnValue().Set(o);
};
When I call this function in javascript it really returns object:
var x = test();
var y = x.toString();
echo(x); // prints [object Object]
echo(y); // prints [object Object]
echo(JSON.stringify(x)); // prints {"code":3.14,"message":"Some message"}
Now I want to implement custom toString() method for the object I'm returning in test(), so that instead of useless [object Object] I would just return the "message". I do not want to edit echo function, I only used echo as an example so that we see what happens when object gets converted to string.
I think it should be set in the "test()" function just like I set code and message I should set "toString" function, but I don't know how. I can only set methods to ObjectTemplate but I'm returning object, not ObjectTemplate.
Here is my custom toString function:
void my_to_string(const v8::FunctionCallbackInfo < v8::Value > &args) {
v8::HandleScope handle_scope(args.GetIsolate());
args.GetReturnValue().Set(v8::String::NewFromUtf8(args.GetIsolate(), "This is
returned from my custom toString"));
};
I cannot assign function to the object:
o->Set(v8::String::NewFromUtf8(iso, "code"), v8::Number::New(iso, 3.14));
// error: no matching function for call to...
I can create ObjectTemplate instead of object but then what? It doesn't allow me to use ObjectTemplate as a return value from my function.
v8::Local<v8::ObjectTemplate> ot = v8::ObjectTemplate::New(iso);
ot->Set(v8::String::NewFromUtf8(iso, "code"), v8::Number::New(iso, 3.14));
ot->Set(v8::String::NewFromUtf8(iso, "message"), v8::String::NewFromUtf8(iso, "Some message"));
ot->Set(iso, "toString", v8::FunctionTemplate::New(iso, my_to_string));
args.GetReturnValue().Set(ot); // this fails: Cannot convert ‘v8::ObjectTemplate*’ to ‘v8::Value*
How do I convert object template with custom toString function to object? Or how to assign a method to object?