From HTML5 Mobile Boilerplate's helper.js:
(function(document){
//all stuff here
})(document);
What does this snippet do or when does it run?
This is a closure, it defines a method which takes an argument document and immediately calls it with document as the parameter.
It runs as soon as it's finished evaluating - so basically straight away.
It creates a temporary, anonymous function and calls it with an argument called document. Presumably it has some local variables that it is hiding from the enclosing scope.
This is a javascript function that executes immediately when the browser encounters it while parsing the page. The function takes one parameter, which is the window.document property (as passed in at the bottom of the function.
If you say:
(function(var1){/*stuff*/})(var2)
That immediately calls the function and passes var2 to the function. Note that the function is anonymous and cannot be called directly. You can read about anonymous functions in general and anonymous functions in Javascript here:
http://en.wikipedia.org/wiki/Anonymous_function#JavaScript
Related
Trying to figure out what this means in javascript.
(function(document) { ... } )(document);
It is isn't using jQuery, so is this just a javascript way of making this wait till document is ready to execute?
Thanks.
This won't wait for the document to be ready, this will execute the content of the function immediately. Putting the function definition in parenthesis makes it an expression, which returns a value being the function, making it directly executable. This pattern is called an Immediately-Invoked Function Expression (IIFE).
This is probably used in conjunction with a minifier like the Closure Compiler.
Inside the function, document is a local variable. This makes it possible for the minifier to reduce its name to a one or two character name.
Note also that all variables defined inside the function will be local : they won't leak in the global scope, which may be interesting if this is only part of the script.
This creates an anonymous function that takes a single argument, and immediately calls it passing document as the argument.
This:
function(document) { ... }
creates a function taking one paremeter.
This:
(function(document) { ... })
makes it (the code, not the function) a valid expression. See here.
This:
(function(document) { ... } )(document);
calls that function with document as a parameter.
It's a basic modularization pattern. In different environments you could've passed some other object instead of document, but nothing inside that function has to know bout it.
This is called self-executed function. It evaluates the anonymous function taking a parameter called document with that parameter passed in.
In client side javascript, whats the difference b/w
$(function(){
....
});
and
function myFunc() {
...
}
(Could not find relevant tutorials on Google)
The first is a DOM ready handler function used in jQuery (a JavaScript library). It is executed when the DOM is fully loaded. Whereas, the second is a simply defined function with name myFunc.
You can read more about JavaScript functions in MDN:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function.
They are totally different uses of function.
The first on calls function $() with parameter function() {}.
The second defines function myFunc.
$() is a shorthand for jQuery's document.ready syntax: Documentation
Code inside a $() will run when the dom has loaded enough to be accessed/manipulated.
The second example is just a normal function declaration and creates a function named myFunc that can be called with syntax myFunc() later.
We use a bit of javascript that overwrites the setTimeout method for IE. This is because in some versions of IE the parameters do not get passed correctly (see here).
I have to load the modified setTimeout script first, because if I load it after the code that calls setTimeout is parsed (not run) then the modifed version does not get called.
What happens when the javascript engine parses files that have method calls to methods at the global scope? Do the mappings to the methods get created at parse time or when the code is executed?
EDIT
I have had a few answers to this question, which give other solutions to this problem, but the problem at hand is not my concern as I already have a solution for it. What I want to gain by this question is a better understanding of how javascript is parsed and run.
Methods are created at when the code is executed.
If the semantics of the code is correct interpreter is able to execute code.
While parsing nothing wasn't be executed.
File after parsing is executed singly one by one , before parsing the next.
Check this out:
We have two js files.
<script src ='1.js'></script>
<script src ='2.js'></script>
In second file we put declaration of setTimeout;
//file2
window.setTimeout = function(){};
In first file we'll checking for setTimeout being overridden
//file1
var f = function() { alert( setTimeout ); };
f();// alerts native setTimeout
setTimeout( f, 1000 ); // We use native settimeout, propably after one second file2 being loaded and executed and function `f` will be alerts the overriden setTimeout
If methods which I added were would be created during parsing. This would have access to it anywhere in the script in which it was created, even before its declaration.
so:
//somefile.js
setTimeout(); // we do not have access to function declared below, so while parsing this wasn't created.
window.setTimeout = function() { alert( 'whatever' ); }
EDIT #2
Fiddle #1 - http://jsfiddle.net/zEaL8/4/ - Allows you to set/reset a native function. To see how the redefinition and calling order works.
Fiddle #2 - http://jsfiddle.net/aKnjA/1/ -Demonstrates that the order of definition does not matter. Notice that the redefinition happens after the browser parses the call to the function.
EDIT
To answer your question: Javascript does not enforce any order of definition of functions. i.e. we can call a function defined afterwards in code. When the browser parses a line of code that calls a function that is defined afterwards, it does not have any clue as to where to find that function. This being the case, it is clear that binding happens only at run-time and not during initial parse. This in effect would mean that your redefinition of setTimeout is what will execute. The only thing to ensure is that the redefinition of setTimeout itself gets executed before any call to that is executed.
To ensure that the redefinition of your new setTimeout is processed first, you can place it in a script block as the first element inside the head node outside load, domReady etc.
i.e. Something like:
<html>
<head>
<script>
window.setTimeout = function() {
alert('new sT');
}
</script>
</head>
<body onload="setTimeout();"></body>
</html>
you can store original setTimeout in a global variable at the beginning of the code and then overload the setTimeot with a new function.
window.oldST = setTimeout;
window.setTimeout = function(funct,x) {
return oldST(funct,x);
}
so if these are the first lines of the js code you will have overloaded the setTimeout function with yours and set the old one in oldST.
What is the calling context of an invoked method or function within another function?
In browsers, the default calling context is the window object. In various situations, how do I avoid this?
If a function is invoked -- for example, by theFunction(); -- within a containing function, is the invoked function's calling context the containing function?
In these two examples
(function ()
{
something.initialize();
}());
and
(function ()
{
something.initialize.call(this);
}());
..., is the calling context the same?
They are not the same. In the following I assume you were talking about this when you mentioned context.
In the first example, inside initialize, this will refer to something. In the second one, it will refer to the global object, which is window in browsers.
What this refers to is determined by how the function was called. There are five cases:
func(), calling a function "standalone": this refers to the global object.
new func(), calling a function as constructor method: this will refer to an empty object which inherits from func.prototype.
obj.func(), calling a function as property of an object: this will refer to the object obj.
func.apply(foo), func.call(foo), invoking a function with apply or call: this refers to the object passed as first argument.
ECMAScript 5 also introduced .bind() [MDN] which enables you to bind this to a certain object, without immediately calling the function.
Now you understand why in your second example, inside initialize, this will refer to window:
The outer function is called "standalone" (first case), so this inside of it will refer to window. Next you are passing this to call, which sets this inside initialize to window (fourth case).
Further reading:
MDN - this, explains all I write above with some examples.
No, they are not the same. The first parameter to the call method sets the value of this inside that function; example 1's this should theoretically contain a reference to something; example 2's this corresponds to the this of your self executing function.
The environment available to a function when it is invoked is based on several things.
the this binding which is different for the initialize method in your example
the actual parameter bindings which are not and a binding for a special arguments object
a binding for the function name, if any
the environment chain at the time the function was created. This is the "close" part of the term "closure". A javascript function "closes over" all the variables that are in-scope when the function object comes into existence.
In your example, only 1 is affected by the choice to use call which has the effect of passing this instead of something as the this value in the method body.
The relevant part of the spec starts at section 10.4.3
The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisArg, and a caller provided argumentsList: ...
Functions don't create context, unless it's a constructor (a function called with new).
In your second example the context is undefined (which gets transformed into the global object , window). In ES5 strict mode it won't be transformed into anything.
I recommend John Resig's interactive JavaScript tutorial on the topic of context.
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(){ … })()”?
I came across a JS file that can be summarized to the code below:
(function(window){
// some codes here
})(window);
I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?
Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?
This is called a immediately-invoked anonymous function. (IIAF for short.)
In this case, you are defining a function that takes in a parameter called "window" that overrides the global window object inside of that scope.
The kicker here is that right after defining the function, you're immediately invoking it, passing in the global window object, so it is as if you used the global reference within the function closure!
Most of the time, the purpose of this is to avoid polluting the global namespace by way of wrapping all potential variables within an anonymous scope.
As far your questions regarding window, the window in parentheses at the bottom is a reference to the global window object. The first window is just a name for a parameter. But in this instance it refers to the global window object since you're using an anonymous self-invoked function. You could call it monkeys and it wouldn't make a difference (of course, you'd have to use monkeys within the body of the anonymous function then, to refer to the parameter). So now, you now have a reference to the global window object within your function.
Yes, the function is invoked once and it is invoked as soon as it is defined. This is because it is a self-invoked anonymous function.
It's a closure. The code in question is a an anonymous function, which will execute with the "window" parameter (end of your snippet). It won't pollute the global namespace.
The first window is formal parameter, while the second one is actual parameter that actually invokes the function. This type of function called self-invoking functions.
The benefit of it is that wrapping functions this way doesn't clutter global scope..
It is an immediately invoked function expression. the grouping operator () around a function expression (essentially a function declaration without a name) means that the enclosed function is evaluated and a function object returned. A function followed by a formal parameter list (another set of ()) causes the function to be called, so:
(function() {
alert('hey');
})();
creates an anonymous function that is called immediately and run once. It doesn't create any global variables and leaves no trace of its existence.
Passing the indentifier window to the function means that it is passes whatever it references. The presumption here (I suppose) is that it will reference a global window object that, in browsers, is the global object. However, in an environment that doesn't have a global window object, it may well be undefined. It is a pointless exercise in my view.
If you are concerned about getting a refernce to the global object, then pass this from the global context:
(function(global) {
// global refernces the global object
})(this);