In my feeble attempt to learn JavaScript, I bought a book which teaches you how to do things in JavaScript, but forgets to mention WHY.
Coming from PHP I am familiar with the typical function syntax:
function name() {return;}
which from what I understand works the same in JS.
Then I decide I want to attempt to use the YUI 3 framework for a small project to continue learning and come across this…YUI Global Object
YUI().use('node', function(Y) {
Y.Node.get('#demo');
});
As far as I understand this is using the ‘use’ function of the YUI() object, passing ‘node’ to the ‘use’ function….but then what…why is it declaring a function within another function call?
Could someone please explain the syntax being used here?
Also a good reference that explains JavaScript general syntax’s similar to php.net would also be beneficial.
Thanks for your help.
Its an anonymous function. Its considered a callback.
In PHP 4 and early versions of PHP 5 you might see something like this:
PHP
In later versions of PHP 5 you can define them as anonymous functions inline.
So, in JavaScript, the old version would look like this:
JavaScript
But by defining an inline anonymous function, you can save the extra clutter and defined function:
Both those functions are equivalent.