Avoiding Nested Anonymous Functions in JavaScript / Sencha Touch / ExtJS - javascript

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 use both ways all the time without thinking too much about what is better. And I believe that in terms of performance if you are worried about a mobile device download time or parsing time then you will end up using some JS Minifier (or maybe Google's Closure Compiler).
Anyway, I do have a criteria that seems helpful to me to decide whether the function should be anonymous or not:
If I had a really good name for the function then it shouldn't be anonymous
What I mean is if your function will be named onSetupReady then the function is not explaining what it does, instead, its name is defining where it should be used (and that would usually be one only place which will call that function). So if that is the case then you can choose to make the function anonymous or not. I usually choose anonymous.
But, if your functions does one just one thing, and that thing in not really obvious, and you are tempted to put a single line comment in the first line of the function (or whatever) to explain what it does. then I won't do that, and I would choose a good name for this function. And I emphasize this rule, even more, when the event which triggers this function is not obvious for that function. Examples:
Anonymous OK
Ext.Window({
listernes: {
beforeclose: function() { // This function has only one purpose and
Ext.Msg.show({ // can be named, but I think it's OK. Because
title:'Close?', // it is really easy to see what it does.
msg: 'Are you sure?',
fn: function(btn) {
if (btn === 'cancel') {
return false;
}
},
animEl: 'elId',
icon: Ext.MessageBox.QUESTION
});
}
}
}).show();
Anonymous NOT Recommended
var insertExtraToolbar = function() {
var containerNbar = theGrid.getBottomToolbar().getEl().parent().dom;
theGrid.elements += ',nbar';
theGrid.createElement('nbar', containerNbar);
};
theGrid.on('render', insertExtraToolbar);

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.

I used to have the same feelings you did when I first started encountering nested anonymous functions.
Now that I've gotten much more used to them I actually find nested anonymous functions much easier to read as long as they're only used in one spot. When code is written that way, all the code I'm interested in is in a single spot and I don't have to jump around the file nearly as much to figure out what the code is trying to do.
Keep in mind, though, that my opinion only applies if the code is only used in one location. If you keep repeating the same anonymous function in multiple places...I still prefer to break it out like your second example.

In a way, you may have answered your own question. The OnReady function is only run once. for maintainability, it might be a good idea to separate out your code so that you have a section for layout, a section for events, and a section for business logic in your code.
One thing to consider perhaps is that Sencha Touch is geared towards mobile devices that may sometimes have limited resources for you to work with. With that in mind, it might be necessary to structure your code to make it as small and efficient as possible. Your proposed code snippet may be ignoring those constraints that mobile platforms have to deal with.

Related

Hooking Function Constructor (JavaScript)

Does anyone know of a way to detect when a new function is created?
I know you can hook the function class constructor but that will only detect new Function() calls, not function func(){} declarations.
I assume the JS engine just creates a default function class when it sees a function declaration instead of looking at the global Function class.
Does anyone know if this is the case or if you can intercept function declarations.
Example function to hook :
function add(x,y){return x+y}
A hook should get the function when it is defined and hopefully redefine it to be able to capture the arguments, this, and return value.
(V8 developer here.)
No, there is no way to intercept all function declarations.
FWIW, this isn't up to individual engines to decide; the JavaScript language provides no way to accomplish this, and engines aim to implement the language without any custom deviations (i.e. neither adding nor removing features).
I can offer two alternative ideas that may or may not serve your purposes:
(1) V8 has a --trace flag which logs all function entries and returns to stdout. Be warned: this tends to produce a lot of output.
(2) You could feed the source of the app you are interested in to a JavaScript parser, and then run whatever analysis (and/or transformation) you want over the AST it produces. This won't catch dynamically generated and eval-ed functions, but it will find all function func() {...} declarations.
The need is game hacking.
In the interest of helping you ask better questions (so that you may get more helpful answers), I'd like to point out that that's not the level of detail that #Bergi was asking for: the general area in which you are active does not provide any hints for possible alternative approaches. Wanting to hook function declarations so that you can capture their arguments and return values is a search for a specific solution. #Bergi's question is: what is the specific problem that you are trying to solve by intercepting all functions?
That said, "game hacking", while being very vague, does sound sufficiently shady that I'd like to humbly suggest that you not only think about whether you could, but alse give sufficient thought to whether you should.

How many anonymous functions can I call

I'm just in the process of studying jquery. And I have the following question. I have a page that relies on js for ajax and reporting to user.
So basically I have created a file with $(function() {}) construct. Inside of that construct I'm using standard jquery functionality to work with my modal windows, smth. like
$('.text-danger').hide();
$(".btnajax").click(function() {})
But now I want to work with another modal window at the same page, not at the same time. What would be a better way:
Continue inside the same anonymous function construct and keep working with IDs and Classes when referencing the specific buttons and form actions?
OR
Create new anonymous function construct? OR
Create named functions and call them when needed?
I would like to build correctly from the scratch, so I don't have to redo everything later when I'm better with JS.
Thank you in advance.
Continue inside the same anonymous function construct and keep working
with IDs and Classes when referencing the specific buttons and form
actions?
This is not a good idea as every time you would do something with the buttons or the form it would access the DOM which is unnecessarily expensive.
Create new anonymous function construct?
Actually, anonymous functions are rarely a good idea as they make your code hard to read. Imagine there are no named functions and everything is anonymous. That would require the reader to always get the context in order to quickly understand what the function is doing
Create named functions and call them when needed?
Especially when reusing that functionality, it's a good idea. But also in terms of readability it is good because the name of the function describes what is happening so when someone (you) read the code again after some time, will know hat is happening without studying the body of the functions.
Apart from that:
I would like to build correctly from the scratch, so I don't have to redo everything later when I'm better with JS.
I can tell you: you will not avoid rewriting parts of your code once the requirements change. That is just what coding is about. You can not foresee every required change to your application. If you try to then you end up having an over engineered code. Instead, you should follow YAGNI.
Generally speaking, for everything that's more than just 5 buttons and a form, a JS file with jQuery is not the way to go. Those times are over. Switch to something that gives you a separation of concerns between model, (model)view and controller.

which approach is better for implementing canvas in html5?

I want to know differences between the two following approaches from efficiency or any other point of views:(these codes are written using HTML5 Canvas)
first one has separate functions including drawScreen() function and event handling functions which all call the drawScreen().
the other one has a function canvasApp() which contains all the functions including drawScreen() inside along with other functions for handling the events. these function again call the drawScreen function inside themselves.
the codes are so long but if the explanation is not clear enough I will put the codes.
It sounds like you either want to have one function that takes a parameter which indicates which function to call, or you want to simply call each function directly. Please correct me if I am wrong.
I would personally go with the separate options. I don't see what encapsulating them inside a global function would bring in terms of functionality or simplicity. As long as the functions are clearly defined and documented I believe this is probably the best approach.
I would be more than happy to give you a more detailed answer, but you are going to have to enlighten us a bit more on your overall architecture (maybe with some pseudocode).
This is a rather religious question.
Javascript is a programming language which combines concepts from procedural, functional and object-oriented programming, so it allows to work in a lot of different programming paradigms.
Option one would be the procedural approach, while two would be the object-oriented approach. We could now have an endless discussion about which programming paradigm is the best, but we would never come to a result.
You have to know for yourself which programming style suits you best and suits your application best.

Is var self = this; a bad pattern?

I find myself needing:
var self = this;
a lot within my javascript 'classes'. Although this is commonly done, it feels a bit wrong.
What I'm hoping to find in this question is a better way to deal with this, or a something to convince me this is quite alright.
Is this the standard way to keep the correct bindings around? Should I standardize on using 'self' everywhere, unless i explicitly need 'this'.
edit: I know exactly why I need this, I'm just wondering if it's considered a bit evil and why. I'm aware there's also the 'apply' built-in javascript function to explicitly define scope when calling a method. Is it better?
As others have said: This "extra variable" is (at some level) the only way to get about the fact that this is a special expression and thus, being not a variable, is not bound in an execution context/closure.
However, what I think you are asking (or what I really want to answer) is:
Should one put var self = this at the top of every method/constructor?
Summary
While I tried this once, and had the same question, I no longer use this approach. Now I reserve the construct for when I need access in a closure. To me it adds a little "hey, this is what I really want!" semantic to my code:
this -> this and self -> this (but really that) in a closure
Questions ala carte:
...Although this is commonly done, it feels a bit wrong. What I'm hoping to find in this question is a better way to deal with this, or a something to convince me this is quite alright.
Do what feels right to you. Don't be afraid to try one method and switch back later (but please try to remain consistent within each project :-)
Is this the standard way to keep the correct bindings around? Should I standardize on using 'self' everywhere, unless i explicitly need 'this'.
"self" is the most common name used. As per above, I prefer the opposite approach -- to use this except when a closure binding is required.
..if it's considered a bit evil and why.
Evil is a silly subjective term (albeit fun sometimes). I've never said it was evil, just why I do not follow the approach. Some people tell me I am "evil" for not using semi-colons. I tell them they should actually come up with good arguments and/or learn JavaScript better :-)
I'm aware there's also the 'apply' built-in javascript function to explicitly define scope when calling a method. Is it better?
The problem with apply/call is that you must use them at point of the function invocation. It won't help if someone else calls one of your methods as the this may already be off. It's most useful for doing things like the jQuery-style callbacks where the this is the element/item of the callback, etc.
As an aside...
I like to avoid "needing self" on members and thus generally promote all member functions to properties where the receiver (this) just "flows through", which is normally "as expected".
The "private" methods in my code begin with a "_" and if the user calls them, that's on them. This also works better (is required, really) when using the prototype approach to object creation. However, Douglas Crockford disagrees with this "private" approach of mine and there are some cases where the look-up chain may thwart you by injecting an unexpected receiver:
Using the "self" bound in the constructor also locks the upper limit of the look-up chain for a method (it is no longer polymorphic upward!) which may or may not be correct. I think it's normally incorrect.
Happy coding.
Yes, this is the standard way.
Function.apply() and Function.call() can help, but not always.
Consider the following
function foo()
{
var self = this;
this.name = 'foo';
setTimeout( function()
{
alert( "Hi from " + self.name );
}, 1000 );
}
new foo();
If you wanted to do this but avoid the usage of a variable like self and use call() or apply() instead... well... you look at it and start to try, but soon realize you just can't. setTimeout() is responsible for the invocation of the lambda, making it impossible for you to leverage these alternate invocation styles. You'd still end up creating some intermediary variable to hold a reference to the object.
Is this the standard way to keep the correct bindings around?
There is no standard, where JavaScript and class/instance systems are concerned. You will have to choose what kind of object model you prefer. Here's another link to a backgrounder; conclusion: there is no conlusion.
Typically keeping a copy var self= this;(*) in a closure goes hand-in-hand with an object model built around closures with per-instance copies of each method. That's a valid way of doing things; a bit less efficient, but also typically a bit less work than the alternative, an object model built around prototyping, using this, apply() and ECMAScript Fifth Edition's bind() to get bound methods.
What could be counted more as ‘evil’ is when you have a mish-mash of both styles in the same code. Unfortunately a lot of common JS code does this (because let's face it, no-one really understands JavaScript's bizarre native object model).
(*: I typically use that instead of self; you can use any variable name you like, but self already has an somewhat obscure and completely pointless meaning as a window member that points to the window itself.)
Just came across this question because my coworkers addicted to self/that variables and I wanted to understand why...
I think there is a better way to deal with this in nowdays:
function () {}.bind(this); // native
_.bind(function () {}, this); // lodash
$.proxy(function () {}, this); // jquery
In javascript and other languages with closures, this can be a very important thing to do. The object that this refers to in a method can actually change. Once you set your self variable equal to this, then self will reliably remain a reference to the object in question, even if this later points to something different.
This is an important difference in javascript compared to many other languages we work in. I'm coming from .Net, so this type of thing seemed strange to me at first too.
Edit:
Ah, okay, you know all that. (maybe still helpful for someone else.) I'll add that Apply (and Call) are more for using from "the outside", giving to a function you're calling a specific scope that you already know about. Once you're inside a function and you're about to cascade further down into closures, the technique:
var self = this;
is the more appropriate way (easy and clear) way to anchor your current scope.
It's 6 years later, and I have some things to add myself:
bind() is now common enough to be used everywhere. I use it often as an alternative. Sometimes it feels clearer. I still on occasion use var self = this;. though.
Arrow functions slowly are becoming viable for usage. The syntax is a bit shorter which is nice, but I think the killer feature really is that by default they always bind to the parent scope.
This:
var self = this;
var foo = function(a) {
return self.b + a;
};
Can now be written as :
var foo = a => this.b + a;
This is the 'most optimistic' usage of arrow functions, but it's pretty sweet.
And just to concluse, there's nothing wrong with:
var self = this;
Most likely this is done as a way to maintain a reference to this when the scope is about to change (in the case of a closure). I don't know that I'd consider it a bad practice or pattern in and of itself, no. You see similar things a lot with libraries like jQuery and a great deal with working with AJAX.
I think there's an argument to be made for always including var self = this in every method: human factors.
It's needed often enough that you wind up having a mishmash of methods accessing this and others using self for the same purpose. If you move code from one to the other, suddenly you get a bunch of errors.
At the same time, I catch myself absent-mindedly writing self.foo out of habit when I haven't needed or added a var self = this. So I think it could make sense to just make a habit of always including it, needed or not.
The only trouble is... this, self, or that are all an ugly pox on your code and I kind of hate them all. So I think it is better to avoid using delegated methods where possible so that you can avoid using this, that or self the vast majority of the time, and use .bind(this) when you might otherwise resort to self/that. It's very rare that using delegates on the prototype is actually going to save you any substantial amount of memory anyway.
A nice side effect of that approach is that you don't have to prefix all your private variables with _, as they will be truly private and the public properties will be called out by the leading this., making your code more readable.
As bobince said, var that = this is better because it doesn't shadow window.self. self = this sounds less awkward to me, but sometimes you get confusing error messages like property myMethod not found on global, because you forgot the self = this line.
I just want to point out that 'self' is equivalent to 'window', try outputting window === self to the console. You should use this pattern with 'that' or something similar as a variable name, avoid using 'self' since it is already in use by the browser (one mistake and you will create yourself a global variable).
Even though it sounds weird, it is better to use 'that' for its name because other developers will immediately know what you were trying to accomplish in your code, avoid using nonstandard variable names.
I believe that this is an important note, but it was only mentioned in one comment, so I wanted to make it more visible.
This was useful at some point in time, using closure to pass scope, but if you're looking for the standard way of developing and handle the scope properly, use :
myFunction.bind(this)
or like some people suggest the arrow function.
On thing to keep in mind : having a variable replace this is not straight forward and can lead to confusion. If it's needed, it's the sign that the code is not structured optimally.
I like it. It is "self"-explanatory. Douglas Crockford has some things to say about this. He states that using "that" is convention. You can see Crockford for free if you scoot over to yui-theater and watch hes videos about Javascript.

jQuery code organization and performance

After doing some research on the subject, I've been experimenting a lot with patterns to organize my jQuery code (Rebecca Murphy did a presentation on this at the jQuery Conference for example).
Yesterday I checked the (revealing) module pattern. The outcome looks a bit reminiscent of the YUI syntax I think:
//global namespace MyNameSpace
if(typeof MNS=="undefined"||!MNS){var MNS={};}
//obfuscate module, just serving as a very simple example
MNS.obfuscate = function(){
//function to create an email address from obfuscated '#'
var email = function(){
$('span.email').each(function(){
var emailAddress = $(this).html().replace(' [ # ] ','#');
$(this).html('' + emailAddress + '');
});
};
return {
email: email
};
}();
//using the module when the dom's ready
jQuery(document).ready(function($){
MNS.obfuscate.email();
});
In the end I had several modules. Some naturally included "private members", which in this case means variables and/or functions which were only of importance for other functions within this module, and thus didn't end up in the return statement.
I thought having connected parts of my code (everything which has to do with the search for example) combined in a module makes sense, gives the whole thing structure.
But after writing this, I read an article by John (Resig), where he also writes about the performance of the module pattern:
"Instantiating a function with a bunch of prototype properties is very, very, fast. It completely blows the Module pattern, and similar, out of the water. Thus, if you have a frequently-accessed function (returning an object) that you want people to interact with, then it's to your advantage to have the object properties be in the prototype chain and instantiate it. Here it is, in code:
// Very fast
function User(){}
User.prototype = { /* Lots of properties ... */ };
// Very slow
function User(){
return { /* Lots of properties */ };
}
(John mentions he is not against the module pattern "per se" though - just to let you know :)
Then I wasn't sure anymore if I was going into the right direction with my code. The thing is: I don't really need any private members, and I also don't think I need inheritance for the time being.
All I want for now is a readable/maintainable pattern. I guess this boils down to personal preference to a certain extend, but I don't wanna end up with readable code which has (rather serious) performance issues.
I'm no JavaScript expert and thus even less of an expert when it comes to performance testing. So first, I don't really know in how far the things John mentioned ("frequently-accessed function (returning an object) that you want people to interact with", lots of properties, etc.) apply to my code. The documents my code interacts with are not huge, with 100s or 1000s of elements. So maybe it's not an issue at all.
But one thing which came to my mind is that instead of just having
$('span.email').each(function(){
var emailAddress = $(this).html().replace(' [ # ] ','#');
$(this).html('' + emailAddress + '');
});
(inside the domready function), I create two "extra" functions, obfuscate and email, due to the use of the module pattern. The creation of additional functions costs some time. The question is: will it be measurable in my case?
I'm not sure if a closure is created in my example above (in an interesting post on the jQuery forum I read the following: "There is a philosophical debate on whether an inner function creates a closure if it doesn't reference anything on an outer function's variable object..."), but I did have closures in my real code. And even though I don't think I had any circular references in there, I don't know in how far this could lead to high(er) memory consumption/problems with garbage collection.
I'd really like to hear your input on this, and maybe see some examples of your code. Also, which tools do you prefer to get information on execution time, memory and CPU usage?
I also don't think I need inheritance for the time being
Indeed. This doesn't really apply to using modules as a namespace. It's about class instance analogues.
Objects you create by making every instance from a completely new {name: member} object are less efficient than objects you create using new Class with Class.prototype.name= member. In the prototype case the member value is shared, resulting in lighter-weight instances.
In your example MNS is a singleton, so there is no benefit to be had by sharing members through a prototype.
I'm not sure if a closure is created in my example above
Yes, it is. Even when no variables are defined in the outer function, there is still a LexicalEnvironment and scope object created for the outer function, with this and arguments bound in it. A clever JS engine might be able to optimise it away, since every inner function must hide this and arguments with their own copies, but I'm not sure that any of the current JS implementations actually do that.
The performance difference, in any case, should be undetectable, since you aren't putting anything significant in the arguments. For a simple module pattern I don't think there's any harm.
Also, which tools do you prefer to get information on execution time, memory and CPU usage?
The place to start is simply to execute the code 10000 times in a for-loop and see how much bigger new Date().getTime() has got, executed several times on as many different browsers as you can get hold of.
$(this).html().replace(' [ # ] ','#');
(What is this supposed to do? At the moment it will read the HTML of the span into a new String, replace only the first instance of [ # ] with #, and return a new String value. It won't change the existing content in the DOM.)
How much Javascript do you have? In my experience, on sites with lots of Javascript code on the pages, performance problems generally come from code that actually does things. Generally, problems stem from trying to do too many things, or trying to do some particular thing really badly. An example would be trying to do stuff like bind handlers to elements in table rows (big tables) instead of using something like "live".
My point is that things like how your modules or functions or whatever get organized is almost certainly not going to pose any sort of real performance issue on your pages. What is motivating you to go to all this trouble?

Categories