我整天都在努力让这段代码正常工作。它应该与 QScript帮助页面中显示的代码相同,但不幸的是它根本不起作用!
class Person
{
public:
QString nm;
Person()
{
}
Person(QString& name)
:nm(name)
{
}
};
Q_DECLARE_METATYPE(Person)
Q_DECLARE_METATYPE(Person*)
QScriptValue Person_ctor(QScriptContext* c,QScriptEngine* e)
{
QString x = c->argument(0).toString();
return e->toScriptValue(Person(x));
}
QScriptValue Person_prototype_toString(QScriptContext* c,QScriptEngine* e)
{
Person* per = qscriptvalue_cast(c->thisObject());
qDebug(qPrintable(per->nm));
return e->undefinedValue();
}
....
QScriptValue per_ctr = eng->newFunction(Person_ctor);
per_ctr.property("prototype").setProperty("toString",eng->newFunction(Person_prototype_toString));
per_ctr.property("prototype").setProperty("myPrint",eng->newFunction(Person_prototype_toString));
eng->globalObject().setProperty("Person",per_ctr);
...
如果我尝试在 JavaScript 中评估以下代码
var p = new Person("Guido");
p.toString();
p.myPrint();
我应该获得:
Guido
Guido
相反,我真正获得的是来自 toString 函数的白色字符串(可能正在调用 Object.toString 函数)和“解释器错误:第 2 行:TypeError:表达式'p.myPrint' [undefined] 的结果不是函数。 ” 来自 myPrint 的错误消息。我想我没有正确地将这两个函数连接到 Person 原型,即使我试图完全按照文档页面进行操作……请有人解释一下我的错是什么?!?谢谢!