What are the benefits of using self executing functions with a framework, such as, Angular?
I am new to Angular but my understanding thus far is the module-based design gives most of the benefits that the Self executing function gives. What am I missing? Is it just a matter of style?
Here is an example by Ben Nadel. I really like the style but want to understand if there are any gains by writing Angular code this way or if it is mostly a style choice.
Mainly, it ensures that your code is not declared on the global scope, and any variables you declare remained scoped within your function.
In this case, it also has the benefit of declaring the objects required to run the code in one place. You can clearly see at the bottom that the angular and Demo objects are passed in, and nothing else. If the code was not wrapped in the function, you'd have to scan through the code to see what the dependencies were.
Personally, I prefer to use a module loader like RequireJS, which effectively forces you to follow this pattern.
That's kind of a opinion question. The main advantage I see on self executing functions is to not create global variables. I had never seen this pattern with angular.
On the example link you gave, it does not seem to have any advantage. The angular variable will exist anyway on a angular application, so you could use angular directly. And the Demo being a module, you can add controllers to it without without messing with the global scope.
I like a lot of self executing functions. But in this case I really don't see an advantage.
Daniel, you said: "if it is mostly a style choice".
I know at least two examples in javascript when "code style" is not only matter of preference but it causes different result.
Are semicolons optional? Not at all.
$scope.test = function() {
console.log('Weird behaviour!')
} //; let us comment it
(function() {} ()); //two functions seem to be independent
is equal to
$scope.test = function() {
console.log('Weird behaviour!')
}(function() {} ()); //but without semicolon they become the one
Another example of "code style" which is not related to self-executing functions:
var x = (function() {
return //returns undefined
{};
}());
alert(x);
/*
that is why, I suppose, while writing javascript code,
we put function brackets in the following "code style":
function() { //at the same line
return { //at the same line, this style will not lose the object
};
}
*/
Code style formation is dictated by unexpected results of such kind.
Last but not least.
With selfexecuting function: a closure is created on function call and keeps your vars local.
A closure is created on function call. That is why self-executing function is so convenient. As Daniel correctly mentioned it is a good place for keeping an independent code unit, this pattern is called module pattern. So when you move from pure javascript to specific framework or vise versa this independence enables code changes to be more fluid. The best case is just moving your module to an angular wrapper and reusing it.
So it is convenient for the purpose of code transmission from one technology to another. But, as I believe, it does not really make sence for specific framework.
Related
I am trying to understand whether or not the concept behind using multiple initialization functions is bad practice. By an initialization function I mean either of the following:
$(document).ready(function(){
//... some code here
}
(function(){
//.... some code here
})();
Time and time again I have seen multiple initialization functions being used and I always thought that this is ultimately a bad practice, but am I really wrong?
Based on that, would anyone care to enlighten me as to whether is it a good or bad practice to use multiple initialization functions?
Edit: removed irrelevant example of a bad use of closure and encapsulation.
Your suspicion is correct in that it's generally a good idea to organize code when you can.
Centralizing initialization functions makes it easier for another developer to figure out which statements are being executed at any given time. This facilitates debugging and becomes increasingly important when multiple developers are working on the same code.
Perhaps consider doing something like this:
$(document).ready(function () {
function findLionelRichie() {
console.log('found Lionel Richie');
}
function findWhomeverElseNeedsFinding() {
console.log('found all the others');
}
(function initialize() {
findLionelRichie();
findWhomeverElseNeedsFinding();
})();
});
That being said, they cannot always be avoided (for example, when calling functions from external libraries). Try to keep it as organized as you can on your end, however.
Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable.
The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:
I'm working on some code, and I came across the following situation inside an archive .js --
(function(Ext) { ..."Here have 2 Ext.Define"... })(Ext);
This code runs normally, but i can't find because the declaration is like that, what is the difference of use simply 2 Ext.Define, the guy who did that code don't work here anymore, but my colleagues said that according to him this is more faster to render, this information proceeds? and if it is, what kind of situations i can use that?
That is an example of a self executing function.
There are some situations when developers use self invoking functions (also known as anonymous functions), like for example when you want an auto-run capability to your app.
My guess is that the previous developer, that worked in your project, wanted just this. Execute the function as soon as it was defined, as some sort of auto-run mechanism.
Also you could use a self invoking function when for example you want to regularly updates a webpage, by using for example setInterval.
(function refreshDB(){
setTimeout(refreshDatabase, 60000);
})()
A self executing function is executed as soon as it is defined.
You can look at it this way:
function(Ext) { ..."Here have 2 Ext.Define"... } represents the definition/declaration of the function, which takes one argument Ext
(function declaration)(arguments), in your case the arguments is only one, namely an object called Ext. This is simply the convention on how to declare and execute a self invoking function in JavaScript.
Also, the following syntax:
(function(arg){console.log(arg)})('Hello World!')
has the same outcome as
! function(arg){console.log(arg)}('Hello World!')
which is just another way of declaring a self-invoking function.
I have been developing an app using JavaScript and all of my scripts are using the Module Pattern. Example:
var MyFunction = (function(){
}());
I saw where someone placed the name of the function inside the calling (). Example:
var MyFunction = (function(){
}(MyFunction));
I add this to some of my page and it still ran normal. Can anyone explain why it would be written with the name of the function inside the ()?
Can anyone explain why it would be written with the name of the
function inside the ()?
No. That coder didn't know quite what they were doing. (A lot tends to get left in when someone doesn't want to break working code)
That said, there are some situations where you would pass something into the IIFE, like window or jquery. You'd treat it as an argument on the inside, though.
The two versions you show are equivalent, but the second one is misleading: the parameter of the IIFE is not used.
You might want to pass (and use) an argument to a module IIFE to alias a dependancy:
var myModule = (function(t) {
//...
var someText = t('some.key');
//...
})(translationModule);
Another use which is opposite to your second example is to declare an argument to the IIFE, and pass nothing. This is to make sure that undefined is... undefined:
var myModule = (function(undefined) {
// Here you're safe from bizare third party code which might define 'undefined'.
})();
In his book Learning JavaScript Design Patterns, Addy Osmani shows several variations of the module pattern:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript
Recommended reading.
Cheers!
I am wondering if it is more or less efficient to encapsulate the main body of your JavaScript code in an object? This way the entire scope of your program would be separated from other scopes like window.
For example, if I had the following code in a JavaScript file:
/* My main code body. */
var somevar1=undefined;
var somevar2=undefined;
var somevarN=undefined;
function somefunction(){};
function initialize(){/* Initializes the program. */};
/* End main code body. */
I could instead encapsulate the main code body in an object:
/* Encapsulating object. */
var application={};
application.somevar1=undefined;
application.somevar2=undefined;
application.somevarN=undefined;
application.somefunction=function(){};
application.initialize=function(){/* Initializes the program. */};
My logic is that since JavaScript searches through all variables in a scope until the right one is found, keeping application specific functions and variables in their own scope would increase efficiency, especially if there were a lot of functions and variables.
My only concern is that this is bad practice or that maybe this would increase the lookup time of variables and functions inside the new "application" scope. If this is bad practice or completely useless, please let me know! Thank you!
I’ve no idea what the performance implications are (I suspect they’re negligible either way, but if you’re really concerned, test it), but it’s very common practice in JavaScript to keep chunks of code in their own scope, rather than having everything in the global scope.
The main benefit is reducing the risk of accidentally overwriting variables in the global scope, and making naming easier (i.e. you have window.application.initialize instead of e.g. window.initialize_application).
Instead of your implementation above, you can use self-calling functions to create an area of scope just for one bit of code. This is known as the module pattern.
This has the added advantage of allowing you to create “private” variables that are only accessible within the module, and so aren’t accessible from other code running in the same global object:
/* Encapsulating object. */
var application=( function () {
var someprivatevar = null// This can't be accessed by code running outside of this function
, someprivatefunction = function () { someprivatevar = someprivatevar || new Date(); };
return {
somevar1: undefined
, somevar2: undefined
, somevarN: undefined
, somefunction: function(){}
, getInitialized: function () { return someprivatevar; }
, initialize: function (){/* Initializes the program. */ someprivatefunction(); }
};
})();
application.initialize();
application.getInitialized();// Will always tell you when application was initialized
I realize you asked a yes or no question. However, my answer is don't worry about it, and to back that up, I want to post a quote from Eloquent Javascript, by Marijn Haverbeke.
The dilemma of speed versus elegance is an interesting one. You can
see it as a kind of continuum between human-friendliness and
machine-friendliness. Almost any program can be made faster by making
it bigger and more convoluted. The programmer must decide on an
appropriate balance....
The basic rule, which has been repeated by many programmers and with
which I wholeheartedly agree, is to not worry about efficiency until
you know for sure that the program is too slow. If it is, find out
which parts are taking up the most time, and start exchanging elegance
for efficiency in those parts.
Having easy to read code is key to my issue here, so I'm going to stick with the modular approach even if there is a slightly longer lookup chain for variables and functions. Either method seems to have pros and cons as it is.
On the one hand, you have the global scope which holds several variables from the start. If you put all of your code right in the global scope, your list of variables in that scope will include your own as well as variables like innerWidth and innerHeight. The list to search through when referencing variables will be longer, but I believe this is such a small amount of overhead it is ridiculous to worry about.
On the other hand, you can add just one object to the global scope which holds all of the variables you want to work with. From inside this scope, you can reference these variables easily and avoid searching through global variables like innerWidth and innerHeight. The con is that when accessing your encapsulated variables from the global scope you would have a longer lookup chain such as: globalscope.customscope.myvar instead of globalscope.myvar or just myvar.
When I look at it this way, it seems like a very trivial question. Perhaps the best way to go about it is to just encapsulate things that go together just for the sake of decluttering code and keep focus on readability rather than having a mess of unreadable code that is only slightly more efficient.
Background:
I have a self-taught hobbyist level of understanding of C++, which has translated into a similar understanding of javascript. As an attempt to understand javascript better, I decided to write a Greasemonkey script that would solve a problem with how Google handles multiple results from the same domain.
I wrote my script, and it was surprisingly easy. Now I feel like this script could be useful to others, so I'd like to release it. Before I do that though, I'd like to be certain I'm not releasing irresponsible code.
I know poor garbage collection is often cited as a problem with extensions, and did some research about what I would need to do in javascript to prevent that. It seems like the answer is any memory that is wrapped in a function will be reclaimed when that function exits. This seems to explain why a few popular scripts I looked at were wrapped in an otherwise useless function.
This leads me to these questions:
What should I do with my basic javascript function to ensure that it doesn't leak memory?
Is this, which I've seen in many scripts, an answer:
(function(){
//code goes here
})();
In the above code, what is the purpose of the first parentheses? It seems redundant to me.
While I was attempting to understand that line, I rewrote it as:
(function main(){
//code goes here
})
main();
The idea being that this was just calling the the previously unnamed function. This didn't work though, why?
I'm more interested in general answers, but in case it's needed here is my current code:
http://pastebin.com/qQWKfnJT
This pattern (wrapping a function in a pair of parenthesis and then placing another pair after the first pair) is called the " I mmediately I nvoked F unction E xpression" pattern (IIFE for short). What it does is define an anonymous function and then execute it immediately. The first set of parentheses mark the function as being an expression, rather than a statement. The second set execute the function returned from the first expression:
// This:
(function(){
// Todo: Add code
})();
// Translates *approximately* to this:
var _anonymous_function_2723113 = function() {
// Todo: Add code
};
_anonymous_function_2723113();
delete _anonymous_function_2723113;
As for why the function does not work when you give it a name, I would recommend reading up on kangaxx's article on the subject, especially where he touches on Named Function Expressions. The short of it is that when you have a named function expression (rather than a statement), the name is supposed to only be available to the function's scope.
So much for three and four - as for avoiding memory leaks, the IIFE is not a way to avoid memory leaks (as #elclanrs has pointed out, it merely helps you avoid polluting the global scope). To avoid memory leaks avoid circular references (and remember, closures can be a source of circular references).
Good luck, and enjoy yourself!
Here is an example, where anonymous functions can be used:
Lets have 4 elements with ids: id_1, id_2, id_3...
We want too loop over each of them and assign onclick event.
for (var i=0; i<5; i++) {
document.getElementById("id_"+i).onclick = function() {alert(i)}
}
When you click elements however each of them will alert the same - 4. The reason is that in the JavaScript closure only the last value is stored for local variables.
What you can do:
for (var i=0; i<5; i++) {
(function(n){
document.getElementById("id_"+n).onclick = function() {alert(n)};
})(i);
}
There are so many answers to this question in SO already... It's a self executing function. It's used in many cases to protect your code from the global scope. It's written in other ways too:
function(){}()
(function(){})()
(function(){}())
!function(){}()
(function(){}).call(this)