开发者

Problems with QScript

开发者 https://www.devze.com 2023-01-12 13:29 出处:网络
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!

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 littera开发者_C百科ly the documentation pages…PLEASE Could someone explains me what is my fault?!? Thanks!


what happens if you remove the brackets after toString and myPrint?


Shouldn't:

Person* per = qscriptvalue_cast(c->thisObject());

be:

Person per = qscriptvalue_cast(c->thisObject());
0

精彩评论

暂无评论...
验证码 换一张
取 消