QScript 的问题
我一整天都在努力让这段代码正常工作。它应该与 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' [未定义] 不是一个函数。”来自 myPrint 的错误消息。我想我没有正确地将这两个函数连接到 Person 原型,即使我试图逐字阅读文档页面......请有人能解释一下我的错是什么吗?!?谢谢!
It’s all the day that I’m trying to make this code working. It should be the same code presented in the QScript help page but unfortunately it doesn’t work at all!
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);
...
If I try to evaluate the following code in JavaScript
var p = new Person("Guido");
p.toString();
p.myPrint();
I should obtain:
Guido
Guido
instead what I really obtain is a white string from the toString function (probabily is calling the Object.toString function) and a “Interpreter Error: line 2: TypeError: Result of expression ‘p.myPrint’ [undefined] is not a function.” error message from myPrint. I suppose that I didn’t connect correctly the two functions to the Person prototype even if I tried to follow litteraly the documentation pages…PLEASE Could someone explains me what is my fault?!? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果删除 toString 和 myPrint 后面的括号会发生什么?
what happens if you remove the brackets after toString and myPrint?
不应该:
是:
Shouldn't:
be: