When we initiate a plan to build a revealing module pattern, what is the biggest difference between constructing the pattern to start this way...
var MODULE = function() {}();
and constructing the pattern to go this way...
var MODULE = (function() {})();
Benefits? Purpose?
Also as an additional question, will either of these techniques allow jQuery to process without passing the $ into them?
Thanks for any feedback!
There's a jsHint option to warn when functions aren't wrapped in parens. The description of the option reads as follows:
"This option prohibits the use of immediate function invocations without wrapping them in parentheses. Wrapping parentheses assists readers of your code in understanding that the expression is the result of a function, and not the function itself."
As for your question about jQuery; Yes, jQuery will be available, provided you've included it, obviously. Having said that, I would still recommend passing '$' or 'jQuery' as a parameter to your function. If you don't, every time you reference it, the engine will have to go up to the parent scope to find it. Not a huge deal, but less efficient, especially if you make heavy use of jQuery. If you pass it in, then jQuery is defined in your function's scope, and won't need to go searching in ancestral scopes for it.
Related
I'm in the middle of trying to figure out at least parts of enyo's fantastic dropzone.js. I'm fairly green with JavaScript train of thought and the prototype paradigm. There's a line of code right on the fourth row that I'm wondering what it does and why would one use a line like that. The line looks as follows:
var __slice = [].slice
Have I understood correctly, that this takes the slice function from the array prototype object and just gives it a bit easier way to refer to it? What is the benefit of this approach? And why the double-underscore at the beginning? I read somewhere, that this would be to avoid conflicts in the global scope, but isn't this already avoided by wrapping the whole code in the
(function() { //code here
}).call(this);
construct?
Have I understood correctly, that this takes the slice function from the array prototype object and just gives it a bit easier way to refer to it?
Yes.
What is the benefit of this approach?
__slice is shorter than Array.prototype.slice (which also requires a couple of extra layers of property lookup), and [].slice in theory creates and throws away an object. So having an identifier for it is just saving some typing and the tiniest, tiniest, tiniest bit of runtime performance.
And why the double-underscore at the beginning? I read somewhere, that this would be to avoid conflicts in the global scope, but isn't this already avoided by wrapping the whole code in the ...
Yes, it is already avoided by doing that. In this case, it would just be a convention the author wanted to use, perhaps to indicate that this is his/her shortcut to Array.prototype.slice. The __ has no intrinsic meaning.
I'm learning Angular and in all the resources I've used so far I saw this in the app.js file:
(function () {
\\\myAngularModules
})();
The most commonl explainantion is an unhelpful "it's just good practice".
Questions:
Is wrapping our Angular JS code in a function really good practice? Why?
What sort of function is it and what does it do?
Please give examples where possible.
This is what is known as an immediately invoked anonymous function (IIFE). It allows us to create a new function scope and immediately run the code so that no variable or other items we create "leak" out and manipulate the global scope.
Leaking of your code into the global can impact other modules or 3rd party code. This also helps protect your code by making you think about what objects you are using that are not declared in your local scope.
http://gregfranko.com/blog/i-love-my-iife/ as a more detailed explanation that covers the general idea other esoteric things like minification benefits.
Is wrapping our Angular JS code in a function really good practice?
Why?
This is good practice and is called module pattern. As a pattern has it advantages and it disadvantages. However, it is one of the most used patterns in the JS world. In a few words, it allows you to declare as you want your variables, your functions etc. without having any conflict with any js code you use in your app.
For further information on the above, please have a look here.
What sort of function is it and what does it do?
It is a classic function. Nothing more nothing less. Using the invoking operator () at the end, we call the function, to be executed. The latter is also known as IIFE, immediately invoked anonymous function.
Here is a common practice in JavaScript:
(function($) {
...code...
})(jQuery);
I understand the wrapper function (it prevents pollution of the global namespace), but many libraries (like jQuery, Underscore, etc.) already define short names ($ and _, respectively) at global scope for me to use. I wonder what the advantage to this approach is. Just to rename jQuery to something shorter? Prevent me from overwriting $? Make it easier to swap in another library later? I guess none of these seem really convincing to me.
Furthermore, I have also seen this:
(function(_) {
...code...
})(_);
Nothing is even renamed here. I have even seen:
(function(global) {
...code...
})(this); // or window, perhaps
What is wrong with just using window directly?
So here's what I'm asking:
Does this practice have a name?
What are the advantages to this practice?
Should I always pass in libraries I'm using rather than use them directly?
Should I pass in this or window as a reference to global scope?
Does this practice have a name?
The syntax is referred to as a self-executing anonymous function. I'm not aware of any special name for passing global objects to the function.
What are the advantages to this practice?
As you've noted, var scoping variables within the function will
help de-clutter the global namepace.
The jQuery example is typically used in plugins so that the plugin can make use of $ while remaining compatible with $.noConflict() (docs)
(function($) {
...code...
})(jQuery);
In general, passing global or reserved objects (like window, document) as parameters can help reduce the size of your script after minification:
(function(window, document) {
// A JS minifier can now minify the all occurrences of `window` and
// `document` within this function.
})(window, document);
Should I always pass in libraries I'm using rather than use them directly?
Should I pass in this or window as a reference to global scope?
Only if minification or conflicting library variable names are a concern.
What are the advantages to this practice?
If the variable ('_', '$', etc) is later overwritten by some other code, your code will continue to work as expected. It will use the value passed in when the wrapper function was invoked.
Should I always pass in libraries I'm using rather than use them directly?
No, but if you have any concerns about the above, it's probably a good practice. Also, if you look up AMD loaders such as Require.js, you will find this a familiar technique, as they do something similar to define the requirements for your module.
Should I pass in this or window as a reference to global scope?
this has the advantage that the code will run where ever there is a global scope. For instance, if you code might possibly run on a Node.js server, there is no window.
I know that Module Pattern is very useful and powerful in Javascript programming.
I recognized that pattern in Eric Miraglia's blog for the first time , but I am wondering one thing.
In other blogs and articles that explain Module Pattern, I notice that their sample codes are slightly different from Eric's article, that is, they use function expression with parenthesis rather than function statement, for example, the article from ben cherry is one of them.
Is there any specific reason to use function expression rather than function statement?
Please explain with easy way, I just entered into Javascript Programming world :)
The Miraglia pattern is the same, defining an anonymous function and executing it. The difference is that in order to use the features of the module, you must have a reference to an instance somewhere. Assigning the module to a global variable (YAHOO.*) is a way to retain the reference at a globally known spot, especially important for frameworks (like YUI).
Sometimes you don't need that reference. For example, if you are writing JavaScript for a web page, you often bind events to functions using selectors (ids / types, etc.) That really removes the need for any global reference to your module function.
Hope that make sense...
Anybody knows what is the meaning of the $ sign before an object attribute.
For example:
pages.$page
I've seen in some javascript codes and I'm not sure if it using some kind of framework.
I've used something like this (this.$el) to access to cached element in Backbone.
Thanks in advance!
As far as javascript is concerned, $ is just another character at the beginning of a variable name, at the end of a variable name, in the middle or all by itself.
As far as some frameworks are concerned like jQuery, it's a character that the framework uses in a specific way (by convention, not because it means anything special to javascript).
For example, in jQuery $(selector) is one of the main functions in jQuery and as such it is a popular convention to assign the resulting jQuery object to a variable with a $ in it like this:
var resetButton$ = $("#reset");
This convention then indicates to the reader that the variable contains a jQuery object.
Other frameworks also use the $ sign, some in similar ways, some in other ways, but in all cases, it's just another character in javascript, but because it stands out, it's often used as a meaningful convention.
Once you become familiar with one of these types of conventions, it can make code a lot easier to read and your brain can actually recognize the meaning of the code even quicker with common, learned conventions. But, these conventions of naming variables a certain way are completely optional.
It is used to mark an element or object as a jQuery object (usually). It's a perfectly valid variable name though.
Many people use $varName to indicate that it is a jQuery variable/property
var $divs = $('div');
var nonJqueryVar = 'hello';