Meaning of statement in JS - javascript

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.

Related

Javascript methods at global scope mappings

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 actually does this javascript snippet mean?

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

How do I read Javascript Closure Syntax?

Based on some code in a lecture by Doug Crockford, I've created this.
var isAlphaUser = (function() {
alert("Forming Alpha User List");
let AlphaUsers = {
1234: true,
5678: true
};
return function(id){
alert("Checking Alpha Users:",id);
return AlphaUsers[id];};
}());
alert("starting");
alert(isAlphaUser(1234));
alert(isAlphaUser(5678));
alert(isAlphaUser(3456));
which gives me this:
Forming Alpha User List
starting
Checking Alpha Users: 1234
true
Checking Alpha Users: 5678
true
Checking Alpha Users: 3456
undefined
Which is quite cool, as it does the expensive setup once only, and every further call is a cheap check.
However, I can't decipher the code that does this. Specifically, I can't understand why I need the "()" at the end of the function declaration.
Can somebody explain how this syntax is working?
() calls a function. function() { } defines a function. Appending () right after immediately calls it1, and the result (also an anonymous function) is assigned to isAlphaUser.
The function() { ... }() pattern is frequently used to isolate variables to an inner scope, so those variables don't become part of the global scope.
In this case, this is what happens:
An anonymous function is run, defining a variable AlphaUsers inside that scope.
That function returns another function that takes 1 parameter. This function is a closure to which the AlphaUsers variable becomes bound (in other words, available). This function checks if the parameter passed in is contained in AlphaUsers (actually, it returns the item at that index, which is just a boolean).
The return value is assigned to a variable isAlphaUser.
Since isAlphaUser is now a function, it can be called to see if the parameter is contained in the AlphaUsers variable, but no direct access to AlphaUsers is available in the global scope (it become a sort of private variable).
1 — Note: As cwolves mentioned in the comments, beware that while () appended directly after the } works in this case, it is only because in this case the function definition is a function expression. If function is the first word on the line, the line becomes a function declaration, and that is all that line can do, the function is not anonymous (it will require a name, otherwise it's a syntax error) and cannot be called immediately inline. See Function Declarations vs. Function Expressions for more info.
The () at the end of the code is separate from the closure issue. By wrapping your function in parens and adding the () at the end you are creating an anonymous function that is run immediately with whatever arguments you pass into ().
Specifically, I can't understand why I need the "()" at the end of the
function declaration.
It creates self-invoking function, in other words, the function is executed as soon as it is parsed.
It is basically same thing when you call a function by suffixing it with () like:
myfunc(); // call this func
The top-level anonymous function returns the function that the isAlphasUser varaible refers to.
You need to call the top-level function, to get the inner-function reference.
Think of it like this, the outer anonymous function is a function factory, i.e., it returns a function.
In order to use any function (even one that returns a function) you must call it.

Need help understanding a javascript function

I'm hoping someone can explain the following usage of JavaScript.
I have a page with a script that looks like this:
(function($){
// code
// and stuff
})(jQuery);
I'm trying to understand what this code does, specifically:
The opening parenthesis at the start
The usage of the $ symbol
The jQuery in parentheses at the end
thanks!
This is an anonymous function.
The specific example you provide is usually used when jQuery (which uses the "$") is conflicting with another library (prototype also uses "$").
What this does is say that whenever "$" is used within the function, it is to reference the jQuery object.
Normal:
$("foo").doStuff()
Conflict avoidance:
jQuery("foo").doStuff()
Using anonymous function to avoid conflict:
(function($){
$("foo").doStuff();
})(jQuery)
At the highest level, it is declaring a function and invoking it in the same statement.
Let's break it down into component parts:
First, we can use $ as an argument/variable name in a function, just like anything else:
function foo($)
{
alert($);
}
foo('hi'); //alerts 'hi'
Second, we can assign a function to a variable:
var foo = function($) {
alert($);
}
foo('hi'); //alerts 'hi'
Finally, we don't have to give functions names - we can just declare them. We wrap them in parenthesis to encapsulate the entire function declaration as a var, which we then call (just like above):
(function($) {
alert($);
})('hi');
In your case, jQuery is some object being passed into the function as the $ parameter. Probably the jQuery library root object, so you can call functions on it.
The parenthesis wrap the anonymous function so it can be called right away with the parameter being a reference to jQuery
$ is a valid variable name in JavaScript, so many frameworks use it for brevity. By including it here as the function argument, you're saying that you want to use $ as an alias for jQuery. This lets you keep your code as short as possible and save your user's bandwidth.
Answered in the first part - you're sending a reference to the jQuery object/framework to your anonymous function.
Briefly:
This declares an anonymous function which accepts one argument, referred to by the local variable name of $, and then immediately calls the function passing as the first argument the jQuery object.
Less briefly:
In javascript a function is declared like this:
function foo(arg1, arg2){
}
Later the function foo can be called:
foo("arg 1", "arg 2");
But in javascript functions are first class citizens; you may, if you choose, store a function in a variable. When doing this the variable name is the function name, so you write it like this:
var foo = function(arg1, arg2){
};
The trailing semicolon is required because a variable declaration (and assignment) is a statement. Later, the function foo can be called:
foo("arg 1", "arg 2");
The advantage here is that you can pass the function to another function, or store it in an array, or whatever. Functions of this sort are called anonymous functions (because they have no function name as such).
Inside the anonymous function foo, as seen above, you can declare local variables which remain withing the scope of that function and do not exist in the scope in which the function was declared. For example, the local arg1 and arg2 variables don't exist in the scope of the variable foo (but they do exist within the anonymous function stored in foo).
This trick allows us to create a private block in which we control what things are named without worrying about stomping over someone else's namespace.
You could write the example you provided as follows:
var foo = function($){
};
fn(jQuery);
Which is the same thing, but has that ugly intermediate variable. What may not be obvious is that the declaration of the anonymous function "returns" a function reference which can be invoked later... or at the same time, merely by adding the function call syntax of ().
What the code is doing is defining an anonymous function, which creates a private scope, and then immediately calling it without storing in a variable. Like this:
function(arg1){
}("arg 1");
I am not entirely sure why there's an extra set of parentheses arroudn the anonymous function definition, but they at least make the code a little more readable/logical. You are merely passing an argument to the result of the parenthetical expression, which happens to be a function:
(function(arg1){
})("arg 1");
All of tis allows jQuery to have a globally-scoped variable named jQuery, but also allows you the user to use the shorthand of $ without conflicting with other javascript frameworks which use the same name for other things.
Let’s first look at the inner function declaration:
function($){
// code
// and stuff
}
This is an anonymouse function declaration with one parameter named $. That function is then wrapped in parenthesis and called by appending (jQuery) to it with jQuery as parameter.

accessing eval'd code through setInterval/setTimeout

i am wondering if i can do some cleanup routines that will auto grab timeouts / intervals. consider this:
var timeout = setInterval(function dimitar() {
console.log("hi!");
}, 1000);
console.log(window);
i had a look through window and can't find any reference to the function that's been passed on. the reference to timeout is there, sure enough. so where does the function 'live' here? is it launching a new instance of the js interpreter to eval/run/keep the code? how can you access it in relation to the timeout uid?
i know i can curry the setInterval function and get it to always store the reference into an array which i can then loop through and clear, but am curious if there's a natural way of doing this
The function you create in your example is using a named function expression. The name is only available within the function. Otherwise, it behaves the same as an anonymous function: you haven't assigned it to a variable and since it's not a function declaration, it doesn't create a dimitar variable in the enclosing scope. The following article may be useful: http://yura.thinkweb2.com/named-function-expressions/
There's no eval-type thing going on: you've just passed in a reference to a function into window.setInterval. This function cannot be retrieved afterwards unless you've assigned it to a variable previously, or it was a reference to a function defined by a function declaration.
If you want to keep a reference to the function around, it's simply a matter of storing it in a variable first:
var dimitar = function() {
console.log("hi!");
};
window.setInterval(dimitar, 1000);
so where does the function 'live' here?
The timeout/interval queue is an internal implementation detail that's not accessible to content JavaScript. It retains a reference to the function passed in to setInterval, but it's not a reference that's visible to you.
Incidentally you should generally avoid using named inline function expressions. Although it's probably OK in this example code, IE's JScript has some serious basic bugs with them that can trip you up if you're not careful. Stick to named function statements (function dimitar() { ... } ... setInterval(dimitar, 1000)) or anonymous inline function expressions (setInterval(function() { ... })).
is it launching a new instance of the js interpreter to eval/run/keep the code?
No, it's the same interpreter and the queue could even be implemented in JavaScript. But the variables behind it are hidden away from the caller.
how can you access it in relation to the timeout uid?
The timeout ID is by design completely opaque. The only defined interface that can do anything with it is the clearTimeout/clearInterval call. There is no interface provided to get the function back from a timeout ID.

Categories