[Qt-qml] Semantics of 'return' in a JavaScript block in QML
Gregory Schlomoff
gregory.schlomoff at gmail.com
Wed Sep 29 13:22:43 CEST 2010
Hi Steve,
Yes, those are indeed anonymous functions, also called lambda
expressions (http://en.wikipedia.org/wiki/Anonymous_function)
They are quite easy to read once you know the syntax:
1. function() is the part that tells javascript you're creating an
anonymous function. You can also define parameters here
2. Then comes the body of your function, between curly braces, as
usual. You can do whatever you want here.
So you've defined an anonymous function that does something with some
arguments and return a value. Now you need to call it, specifying the
value of the arguments. That's what the last pair of () does. Here, it
calls the function without any arguments.
>why is it such a common construct when using javascript?
Well, because once you get used to it, you can't live without it.
That's why they are part of C++0x, and that's why a guy even did a
tricky implementation of then in pure C++:
http://matt.might.net/articles/lambda-style-anonymous-functions-from-c++-templates/
But the real reason in this case is that without them, every single
QML expression would need to have it's own named function to evaluate
it.
For instance, you wouldn't be able to write:
Rectangle {
height: width * 2
}
But you would instead need to write:
Rectangle {
height: calcRectHeight(width)
function calcRectHeight(w) {
return w * 2;
}
}
Hope this helps you! (also, hope this is correct, I'm not a qml
engineer, so those are just my guess, and may very well be incorrect
:)
On Wed, Sep 29, 2010 at 5:50 PM, Stephen Kelly <steveire at gmail.com> wrote:
> Sorry for dragging this up again. I forgot to reply at the time.
>
> Pertti Kellomäki wrote:
>
>> On 09/16/2010 03:37 AM, Kennedy Aaron (Nokia-MS-Qt/Brisbane) wrote:
>>> Internally
>>> the above is actually evaluated like this:
>>>
>>> Text {
>>> text: (function() { if (condition) { return "A"; } return "B"; })()
>>> }
>>>
>> This would actually be a good way to document it, at least to a former
>> Lisp-head like myself ;-)
>
>
> As a C++ head I rarely see syntax like the above and I find it quite
> difficult to parse. I've seen stuff like that when reading jQuery.js and
> code that uses it, but what is actually happening and why is it such a
> common construct when using javascript? Got links?
>
> It looks like a unnamed function is defined 'inline' inside some (), like a
> python lambda function or so, and then called immediately. Is that what's
> happening?
>
> All the best,
>
> Steve.
> _______________________________________________
> Qt-qml mailing list
> Qt-qml at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-qml
>
More information about the Qt-qml
mailing list