I’ve started using the Sencha Touch / ExtJS JavaScript framework and have am noticing a wide use of nested, anonymous functions. For example, this is a common way to start your app:
Ext.setup({
blah: blah,
onReady: function() {
my
fairly
long
startup
code }
});
It’s been a while since I’ve done JavaScript programming; to me, defining a nested anonymous function like this–inside of a function call–is not as easy to read as the following:
Ext.namespace('myvars');
myvars.onReadyFcn = function() {
my
fairly
long
startup
code
};
Ext.setup({
blah: blah,
onReady: myvars.onReadyFcn
});
I understand there are some real benefits to using anonymous functions in certain situations (e.g., maybe it’s one-time code, maybe you don’t want to add another function to the global namespace, etc.). That said, is there anything technically wrong/detrimental to using this latter (perhaps more verbose) method if you find it easier to read?
Thanks!
I don’t think there is anything wrong using separate functions, depending on the purpose. For a setup function or onReady functions I will like anonymous functions, for callback functions that are really small piece of code like 1 or 2 simple line I will use anonymous functions. For callbacks I often like to use a separate function however, I find it easier to read and especially with most frameworks giving an easy way to pass parameters to the callbacks when making XHR.
However, one advantage nested anonymous functions gives you is the closures around variables that sometimes you might end up needing to pass as parameters if you separate the function.
It is a very tough question to answer because it will be a question of style, performance, purpose that will be different depending what is the purpose of the code you’re writing.