I want to know the difference between following javascript functions. Can someone help whats the difference and in what circumstances do we need to use these two functions?
define(function () {
});
the second one is self executing function which is below
(function() { })();
Update
I am using requireJS
Your question title mentions a "jQuery function" but there is no jQuery in the code you've shown.
The first bit of code:
define(function () {
});
...calls a function named define and passes an anonymous function as a parameter (some kind of callback?)
The second:
(function() { })();
Defines an anonymous function and calls it immediately.
"whats the difference and in what circumstances do we need to use these two functions?"
Consult the RequireJS API documentation for guidance on when to use the define() function. As for an immediately-invoked-anonymous-function as in your second example there are many different reasons why you might use such a structure, e.g., a common reason is to create working variables and/or nested functions without creating globals.
To my way of thinking comparing the two (without more context, anyway) doesn't make any more sense than comparing setTimeout(function(){ },1) with (function() { })(); (or comparing any other random function that takes a function as a parameter).
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 aware of functions being declared and immediately called, like so
(function(arg) {...}(value))();
but what does this mean:
functionName(function(params){...});
It is in the (first non code line of the) demo/demo.js file of the Ace editor and it is the worst javascript code I have yet encountered. I want to know if it is really poorly written or if I am too novice to decipher it.
In this case,
outerFunc(function(params) { ... })
contains the definition of their module in an anonymous function, which outerFunc uses to control how it's defined. In the code you're referring to they use the define function from RequireJS to do several things, including specifying dependencies and executing context.
define() is part of the CommonJS modules specification, and needs to be implemented differently on different JavaScript platforms you're using. This code design is more than reasonable; it's following the proposed specifications that may be a core part of the language in the future.
An anonymous function is passed to the function functionName().
If it's poorly written, or you are too novice, that depends, because it might be just a legit well usage of this style.
It is not poorly coded. That is an anonymous function being passed to the function functionName. That function will have a name local to functionName and can be called inside it. This can be extremely useful in a lot of cases.
sort(my_arr, function(obj1, obj2){
return obj1.age*obj1.color - obj2.age*obj2.color;
}
);
function sort(arr, compare){
// Sorts arr of objects using compare(arr[i], arr[j]);
}
This would allow you to implement a single sort function sort which works for all possible objects as long as the caller provides a compare function for that type of object.
(function(arg) {...}(value));
This is not a function call. You probably meant (function(params) {...}(value))(someArgs);.
functionName(function(params){...});
This is a call to function functionName, passing that anonymous function in as a parameter.
This is (essentially) the same as:
var f = function(params) { ... };
functionName(f);
or:
function f(params) { ... };
functionName(f);
Consider:
function functionName(f) {
f();
}
That ... now gets invoked.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
Hello all,
I have seen several JavaScript files using this notation:
Start of JavaScript file:
(function() {
// All functions go here.
// Can someone say what the wrapping nameless function is used for?
})();
Also with the prototype library, this seems possible:
function $() {
// Prototype $-wrapping function.
}
Can someone please explain the above two code fragments, their uses and their differences? Some keywords which would help me find more about this notation/technique (how it is named) would be helpful too so I can run a Google search on it... :)
Thanks!
In your first example, people surround their code in an anonymous function for scoping reasons, to avoid global namespace cluttering. That weird parentheses syntax is used to define and execute the function all in one step; the () at the end has the meaning of executing the function itself.
So inside that anonymous function you could define function apple(){} and it would only be accessible inside that anonymous function. This is good if you're making a library and want only certain things to clutter your global namespace.
Your second example is just a simple function called $. Many libraries like to use this name because it's short and concise, and since you need to type it every time you want to reference the libraries namespace, the shorter, the better.
I searched for "javascript wrapping function" and the first hit was this, which says:
This method doesn't add any new symbols to the global or LIB spaces.
I don't understand the second part of the question: function $() { ... } isn't a "nameless" function: it has the name $! If you like functions named $ it's the most straightforward way I know of to make such a thing.
An annonymous function is defined
function() {
}
and then immediately called
()
The extra () enclosing the function is to force the interpreter to treat the function as an expression. Javascript treats any statement starting with the function keyword as a declaration so it could not otherwise be immediatly called.
The purpose is to avoid polluting the global namespace. All variables defined in the function will be local to the function.
Google for module pattern.
retracted in favor of answer to: What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
First one is called immediate function. You can read more about this function pattern here.