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.
Related
If have a callback that is activated repeatedly such as the following...
Template.foo.rendered = function() {
$(this.firstNode).droppable({
// other arguments
drop: function() {
// some really long function that doesn't access anything in the closure
}
});
}
Should I optimize it to the following?
dropFunction = function() {
// some really long function that doesn't access anything in the closure
}
Template.foo.rendered = function() {
$(this.firstNode).droppable({
// other arguments
drop: dropFunction
});
}
In this case, the rendered callback is a Meteor construct which runs asynchronously over a DOM node with template foo whenever they are constructed; there can be quite a few of them. Does it help to declare the function somewhere in a global closure, to save the Javascript engine the hassle of keeping track of an extra local closure, or does it not matter?
I don't believe that in modern browsers that there will even be a difference. When creating a closure object, V8 determines what variables your function uses, and if you don't use a variable it won't put it in the closure object(I read this somewhere online a while back, sorry I can't find the link*SEE BELOW*). I assume any browser that compiles JavaScript would do the same.
What will be optimized is the creation of the function. In the second example the drop function is created at the same time as the rendered function, in the first it's re-created every time the rendered is called. If this was in a long for loop that might be worth optimizing.
I personally think the first example is a lot easier to read and maintain. And as I said in a comment on the question you(or the person editing this code in the future) could accidentally overwrite the function variable(in an event handler or something) and you could have a hard to find bug on your hands. I would suggest saying with number 1, or wrapping everything in a self-executing function so dropFunction has a smaller scope and less chance of being overwritten, like so:
(function () {
var dropFunction = function() {
// some really long function that doesn't access anything in the closure
}
Template.foo.rendered = function() {
$(this.firstNode).droppable({
// other arguments
drop: dropFunction
});
}
})();
EDIT: I found the link, it was actually in a blog post about a closure memory leak in Meteor!
http://point.davidglasser.net/2013/06/27/surprising-javascript-memory-leak.html
Here's the portion I mentioned:
JavaScript implementations (or at least current Chrome) are smart enough to notice that str isn’t used in logIt, so it’s not put into logIt’s lexical environment, and it’s OK to GC the big string once run finishes.
I'll start this by saying I don't know anything about meteor :/ but if I'm understanding what happens correctly, basically:
Template.foo.rendered
Gets called repeatedly. When that occurs, you construct and object + define a new function on it "drop" which is eventually invoked. If that is the case, you are better off from a performance perspective defining drop once at parse time. But the benefit probably depends on how often rendered is called.
As for why - I posted something similar here:
Performance of function declaration vs function expressions in javascript in a loop
And I think #soktinpk's answer I think is a great summary.
If you look at the jsperf in the above link it may not initially seem directly applicable, but if my assumed statements above are true it is in fact is - because the question at hand boils down to how expensive is to define a function at runtime vs parse time and are you defining this function at runtime over and over again.
If you look at the performance of the loops where a function is defined at runtime vs the loops where functions are defined at parse time (or defined at parse time and hoisted), the parse time loop run significantly faster.
I believe that the equivalent of what meteor is doing in your example is probably something like this jsperf: http://jsperf.com/how-expensive-is-defining-a-function-at-runtime2
What I have done here is created two loops that simulate your scenario being invoked over and over again. The first invokes a function that creates and object and function and passes it to another function for invocation.
The second creates and object that references a function and passes it to another function for invocation. The difference in performance looks significant (58% in chrome).
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.
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.
I am learning javascript and jquery and wondered whether it is good or bad practice to nest all my functions within $(document).ready(function). Is there any difference between this:
function someFunction()
{
return someThing;
}
$(document).ready(function()
{
// some code
...
someFunction();
});
and this:
$(document).ready(function()
{
// some code
...
function someFunction()
{
return someThing;
}
someFunction();
});
Be gentle - I'm pretty new to this!
You forgot at least one :-)
function someFunction()
{
return someThing;
}
$(someFunction);
Generally there is no difference between: $(document).ready(argFunc) and $(argFunc).
The other variations you listed have all different scopes for different things.
For example, in your 2nd block you declare someFunction inside a non-global scope, while your first and my example declare it in the global scope, which has implications for reachability.
Also, technically, with both of your variations you produce one extraneous function call. Because in this case, all you call is one function (which you can also write like my example).
UPDATE1:
To add some additional info and to further the discussion about scopes - JavaScript has very loose requirements for existence of variables. If it doesn't find them in the current scope, it wall just traverse the call chain upwards and look for it - until it finds it or not. That is why you can access the jQuery object ($) from anywhere.
There is however this:
someFunction($) {
// You can use $ here like always
return someThing;
}
$(someFunction);
This means, that the handlers (there can be more than one) for the document ready event of jQuery get passed jQuery itself as an argument.
If you specify this parameter for your function, you'll use that one, if you reference it. Otherwise, you are using the global one. That reduces the length of the upward look-up - chain.
That is completely irrelevant from a performance stand point.
But, by specifying this as a parameter, you make it absolutely clear where the jQuery object is coming from. Even that might be irrelevant.
I just wanted to show, that these callback-type functions in jQuery often take parameters that are useful.
So if you are ever stuck and need access to some object you don't have, it might be worthwhile to check the jQuery docs to see, if there is not a parameter, that does what you want.
To conclude this update, I very much like the first comment to the question, which is a much better answer than mine.
UPDATE2:
On the point of multiple callbacks for document ready (or any event binder in jQuery for that matter):
You can do this:
$(func1); // or $(document).ready(func1);
$(func2); // or $(document).ready(func2);
Both will get called as soon as jQuery fires its document ready event. That might come in handy depending on the perspective. Some would say, it encourages spreading your logic around. Others might say, it allows for cleaner separation of all the things that need to be done on document ready.
yes. The first way puts someFunction in the global scope so that it can be called by anyone. If you intend this function to be "private" and only callable by some code then the 2nd way is preferred. Generally you should prefer the 2nd way unless you need to export the function into global scope.
The differences are subtle, but worth bringing up.
Declared functions outside of DOM ready:
If you don't call the functions until DOM ready, then this is more efficient since it is registering the functions before waiting for the DOM to load (Edit: As is noted in the comments, there will be a slight performance penalty in accessing global variables due to scope resolution). This is very minor and probably not noticeable.
More importantly, you functions become globals, and you can clutter the global scope if you're not namespacing properly:
var myFuncs = {
someFunction : function() { ... },
someOtherFunciton : function() { ... }
};
Declared inside DOM ready:
Functions are no longer globals, but your functions are registered along with your other DOM ready code.
I would say it's fine to go either way in most cases, but definitely declare your functions under one namespace.
First off, functions are typically only declared if they are going to be used more than once. If you put a function inside the $(document).ready(function) then it won't be available outside the scope of the $(document).ready(function). Check out an article on Javascript Scope.
This is because $(document).ready accepts a function as a parameter and in your two examples you are declaring an inline function (that's the function () {} code in there). Check out a discussion of inline functions vs parameterized functions.
So, it boils down to deciding if you are going to use someFunction() more than once. If so, put it outside the $(document).ready function. Otherwise, you don't really need a function since you are just calling it once.
As long as someFunction() does not try to manipulate the dom, there is no difference. $(document).ready is called after all elements in the dom have loaded and can be accessed with javascript. If you try to manipulate an item in that page with javascript before it loads, it wont be there and the code will break.
When you wrap your JavaScript code in a function like this:
(function(){
var field = ...;
function doSomthing(){...
...
})();
I noticed that this fixes scoping problems for me on a lot of web pages. What is this practice called?
The pattern is called self-invocation, a self-invoking function. It can create a closure, but that is an effect of the pattern (perhaps the intended effect), not the pattern itself.
To clarify a bit for the comments below, most of the time it's creating a closure, it keeps your variables scoped to that local closure, as to not create global variables, it both keeps things clean and avoids any potential unwanted changes to those variables.
There are some excellent answers here that explain the why a bit more: How does a javascript closure work?
It's only a creating closure when something inside that scope is exposed to an outer scope, which is usually the case, but I can't be sure for your example without seeing more code. If nothing is exposed then no closure's created...otherwise it's just an anonymous function executing immediately.
The })(); format at the end, as opposed to }); is actually calling that closure to execute immediately, with no parameters. If you had something in it, for example })(something); then that something would be passed as the first argument here: (function(somethingParam){.
The wrapping function is called an anonymous (it has no name and it isn't assigned to a variable) self-executing (it executes immediately, by itself) function.
I don't remember seeing an exact name for this pattern, but it prevents variable from leaking into global scope.
Ben Alman presents an interesting argument on the commonly use terminology for this "pattern".
His blog post about it is here (http://benalman.com/news/2010/11/immediately-invoked-function-expression/).
If his post is too long for you here is my summary (I still recommend reading it as this summary leaves out a lot):
If you want a named function to be self executing/invoking it would should look like this:
// Hello, my name is "foo". I am a named function.
// When I am invoked I invoke my self when I am invoked.
function foo(){
foo();
}
If you want an anonymous function to be self executing/invoking it should look like this:
// Hello, I have no name...
// (though I am assigned to the variable "foo" it's not who I am).
// When I am invoked I invoke my self when I am invoked.
// In ECMAScript 5 I no longer work. :-(
var foo = function(){
arguments.callee();
};
If you want an anonymous function to be immediately executed/invoked it should look like this:
// Hello, I have no name. I am immediately invoked.
// People sometimes call me a "self-invoking anonymous function"...
// even though I don't invoke myself.
// Ben Alman calls me an "Immediately-Invoked Function Expression"...
// or "iffy" for short.
(function(){ /...code.../ }());
My own thoughts on the matter:
The other answers are correct; what you are asking about is commonly referred to as a "self invoking anonymous function."
However, that terminology doesn't accurately reflect what is really happening; "Immediately-Invoked Function Expression" (aka "iffy", for short) seems like a more appropriate term.
Fun facts to impress your friends:
You can create an Iffy like this, too:
!function(){
alert("immediately invoked!");
}();
or
+function(){
alert("immediately invoked!");
}();
or if you are really cRaZy ( example ):
!1%-+~function(){
alert("immediately invoked!");
}();
in most browsers (if not all, I'm not sure) and the effect will be the same (facebook uses the ! version).
Douglas Crockford and the YUI team call it the module pattern.
What is this practice called?
It's called an immediately-invoked function expression, in short: IIFE. It defines a function in an expression, which is then executed on its own (without assigning the function to any identifier). It sometimes is also called immediately executed function expression (IEFE).
Before Ben Alman wrote his blog post on them, they were also known as self-invoking (anonymous) functions, a term which became uncommon since then. It was technically imprecise, hinting at a recursive invocation which does not actually happen.
For details on the syntax see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.
I noticed that this fixes scoping problems for me on a lot of web pages.
Yes, the purpose of this pattern is to introduce an extra scope by executing a function.
The pattern also is sometimes extended with a return value, known as the (revealing) module pattern, or with a name for the function to allow recursive invocations.
It's been around longer than "patterns". It is a common idiom in scheme/lisp primarily used for encapsulation especially when doing meta programming.