我尝试将嵌入式js引擎从非常旧的nspr更改为v8,并且遇到了这个功能的麻烦。
这就是我想要做的事情:
// C++
class myClass {
public:
myClass();
static void myClassConstructor(const v8::FunctionCallbackInfo<v8::Value>& args);
static void myClass_method1(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Persistent<v8::Function> constructor;
}
void JS_InitmyClass(Isolate *isolate, Local<Object> global) {
v8::Local<v8::FunctionTemplate> f = v8::FunctionTemplate::New(isolate, MyClass::myClassConstructor);
f->SetClassName(v8::String::NewFromUtf8(isolate,"myClass"));
f->InstanceTemplate()->SetInternalFieldCount(1);
f->PrototypeTemplate()->Set(String::NewFromUtf8(isolate, "method1"), FunctionTemplate::New(isolate, myClass_method1->GetFunction()));
global->Set(v8::String::NewFromUtf8(isolate,"myClass"), f->GetFunction());
if (myClass::constructor.IsEmpty())
myClass::constructor.Reset(isolate, f->GetFunction());
}
void myClass::myClassConstructor(const v8::FunctionCallbackInfo<v8::Value>& args) {
EscapableHandleScope handle_scope(args.GetIsolate());
myClass* ref = new myClass();
args.This()->SetInternalField(0, External::New(args.GetIsolate(), ref));
args.GetReturnValue().Set(handle_scope.Escape(args.This()));
}
void myClass::myClass_method1(const v8::FunctionCallbackInfo<v8::Value>& args) {
// Here I want to create a new object (outside a 'new' js context) and return it
EscapableHandleScope handle_scope(cx);
myClass *ref = new myClass();
Local<Function> f = Local<Function>::New(cx, myClass::constructor);
Local<Object> newobj = f->NewInstance();
newobj->SetInternalField(0, External::New(cx, ref));
return handle_scope.Escape(newobj);
}
// Js
myClass.prototype.js_method = function () {
}
a = new myClass(); // a is [Object myClass] and got method1 & js_method available
a.js_method(); // ok
b = myClass.method1(); // b is [Object myClass] but only method1 is available
b.js_method(); // not ok
据我所知,对于a,原型已根据需要进行了更改,但对于b,使用了旧原型,因此js_method无法使用。对吗? 那么如何在没有js&#39; new&#39;的情况下在v8中创建一个对象,并且具有相同的行为?
我以前尝试过很多东西......如果有人可以帮助我,他会非常欢迎:-) 祝你有个美好的一天。