JavaScript Module Pattern written two different ways with same results - javascript

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!

Related

Is there a way to evaluate a function defined as a string by using eval()?

I would like to store a function definition in a string, like for example:
var funcString = 'function(){ return 4+4 }'
Can I use eval() to evaluate the function?
Like for example:
var result = eval(funcString)
which will evaluate the string in funcString as a function and return 4+4 (8) in result.
edit: So from what you've told me I understood that I shouldn't use eval in that way, but for my case I don't think there is another way.
I would like to define a set of rules in a separate file and I want to instruct my Javascript Library to look into this file and search for the rules. The following is an example of a rule:
rule('logOut', (function() { return !JSLibrary.compareUserDetails })(), (function() { console.log("\n\nError: logged out user did not match\n\n\n") })())
I would like to evaluate both of the functions defined in the rules and I think that eval is the only way to do it. I don't know if there exist any other.
Fair warning, eval is "evil." I'll answer your question regardless, but you might want to rethink using eval.
In JavaScript, functions are values, just like 5, 'Stack Overflow' and document. In fact, what function myFunction(args) { body } does is create a function and throw it into a variable called myFunction*.
Say you wanted to take that function and put it into another variable. You can just say var otherVariable = myFunction. And if you want to call that function, you can just say otherVariable().
But say you want a function that isn't bound to a name, for instance if you're passing it to another function. You can use an anonymous function, defined as function(args) { body }. That's what's inside the string you're eval-ing. Anonymous functions are just like any other function, and you can call them as such. Actually, you can even call them right out of the result of eval by tacking on some parentheses at the end.
Unfortunately, it's not that easy though. You can't just write a line of code with an anonymous function definition and expect it to run: you will instead get an error complaining about it not being named. To fix this, throw some parenthesis around the definition to force it to be an expression instead of a statement.
Your final working code will look like this:
var funcString = '(function(){ return 4+4 })'
var result = eval(funcString)()
Sure, you should never use eval for this particular use, but I hope you learned a bit about JavaScript from this answer anyways.
* There's more to it than that, such as hoisting, but that doesn't really matter in this explanation.
Use of an immediately invoked function expression can call a function with eval.
document.body.innerHTML = eval('(function(){return 4+4;})()');
WARNING: do not ever do this: it's insecure, a performance-killer, harder to read/understand, etc

Declaration on ExtJS

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.

Self executing functions with AngularJS

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.

Self-invoking function and params?

I've seen the next way of writing self-invoking functions:
(function (app) {
app.foo = {
bar: function(){}
};
}(App));
Where App is a global object.
I wonder, why do we need to pass App as a param into a function? Why don't just use this:
(function () {
App.foo = {
bar: function(){}
};
}());
I see only one advantage of using the first way. If we for some reason rename the App object, then we can easily rename the param in brackets and our code will work as it works. But in case of the second way we will probably need to rename App in all places where we use it.
Are there other differences?
It means that the contents of the function – with regards to the app identifier – are agnostic to the global (or parent) scope.
One of the scenarios in which this is done is, for example, with jQuery, when you don't want to assume that the jQuery object is called $ (e.g. if no-conflict mode is on), but you do want to call it by that name. Passing it through an anonymous function like this (i.e. (function($) {})(jQuery)) allows you to generate a locally-scoped alias that doesn't interfere with the external meaning of the name $ in the parent/global scope.
The other answers explain the benefit of having a locally scoped copy. There are a few other benefits too:
As a micro-optimization it reduces scope lookups (it's less expensive to find a local var than a global one).
It can help in the minification process as all your params are reduce to single letter named vars.
It gives you a pseudo dependency management technique...in your example, you know your code is dependent on App.
For example, many libraries use the "$" character as a shortcut for their main function (e.g. JQuery). This is convenient, but can cause a clash when using multiple libraries. So, you could pass JQuery in like this:
(function($) {
// Code
var nav = $('#nav');
// More code
})(JQuery);
That way, you can still use the convenient shortcut, but you can also avoid clashes (as long as you also configure the libraries not to use the "$" shortcut).
You can also use it to redefine global variables locally to ensure they contain whay you expect:
(function($, undefined) { ... })(jQuery);
Where undefined is now the expected undefined. Also see: What is the purpose of passing-in undefined?
Most other uses are well covered in the other answers.

What is Javascript collision?

Any best practices around it?
JavaScript collision is when you have two global objects with the same name, and one overwrites another. For example, you might reference two libraries that both use a function named $ at the root object (window) for a query function. The idea is that you should use as few global objects as possible. The best way to do this is to create a namespace for any JS you write, just like any other language:
var myApplication = {};
And then add any subsequent functions / objects inside the namespace:
myApplication.init = function () {
}
google sometimes better than stackoverflow
http://javascript.about.com/od/learnmodernjavascript/a/tutorial22.htm
I think it is a concept which detects when two objects collide, this technique is especially useful when creating javascript-based games.
This also refers to collision of different javascript libraries used in one page for example jquery and prototype used in one page and nothing works because of collision usually because of popular $ sign.
Javascript has first class, lexically scoped functions, in other words in side of a function, when you call a variable, it checks itself for an instance of that variable, then checks it's parent function.
<script>
var foo = "test1";
document.write(foo+"\n"); //test1+ a linebreak
(function(){
document.write(foo+"\n"); //test1+ a linebreak
var foo = "test2";
document.write(foo+"\n"); //test2+ a linebreak
})();
document.write(foo+"\n"); //test1+ a linebreak
</script>
I thought it was something that happens when a Mummy Javascript and a Daddy Javascript, who love each other very much want to eval a baby Javascript.
My teacher wasn't very clear on this point however ...

Categories