Need some help understanding this JavaScript - javascript

I have the following strange looking code in a js file and i need some help in understanding whats going on. What im confused about is why is the whole thing put in paranthesis ?. What does that mean ?
(function() {
var someobj = window.someobj = [];
var parentId = '#wrapper';
$(document).ready(function() {
//some code here
});
$(document).ready(function() {
//some code here
}
});

If the code that you provided is complete (with the exception of what is inside the two $(document).ready(function() {}); statements), than this code does nothing and the function is never executed. It's the same with or without the wrapping parenthesis.
By wrapping a function in parenthesis, you can create an anonymous function. However, the function must be executed immediately, or stored in a variable (which would negate the anonymous part). You'll often see this technique to avoid polluting the global scope with variables that are temporary or only used for initialization of a larger application. For example.
(function() {
// Do initialization shtuff
var someLocalVariable = 'value';
})();
// Notice the `();` here after the closing parenthesis.
// This executes the anonymous function.
// This will cause an error since `someLocalVariable` is not
// available in this scope
console.log(someLocalVariable);
So then, what your code is missing is the (); after the closing parenthesis at the end of the function. Here is what your code should (presumably) look like:
(function() {
var someobj = window.someobj = [];
var parentId = '#wrapper';
$(document).ready(function() {
//some code here
});
$(document).ready(function() {
//some code here
});
})();

It does not look like this code is complete. As written, this code will do nothing at all. Are you missing a close paren and an extra set of parentheses at the end?
In JavaScript, there is no module system, and thus no way to create a module with its own top-level definitions that don't conflict with other modules that might be used.
In order to overcome this, people use anonymous function definitions to avoid name conflicts. What you do is create an anonymous function, and execute it immediately.
(function () { /* do stuff */ })();
This creates a function, and then executes it immediately with no arguments. Variables defined using var within that function will not conflict with variables defined anywhere else, and thus you get the equivalent of your own, private namespace, like what a module system would provide.

The outer parentheses are redundant here (there is a typo in your code though, I think you're missing the closing );). Sometimes people will wrap a function in parentheses for clarity when invoking the function immediately, e.g.
(function($) {
//some jQuery code
})(jQuery);
Within the function above, the parameter $ will have the value of the outer jQuery variable. This is done within jQuery and jQuery plugins to prevent the $ symbol clashing with other frameworks.

I'm going to assume that this is actually part of an anonymous function definition and that's why it's in parenthesis. I could see doing this if there was some sort of logic going to make window.someobj change based on different conditions, but have code further along do the same thing.

The parenthesis aren't actually necessary as far that this code goes. This code doesn't seem complete though. The function initializes by setting a variable to some object on the page and then setting another constant. Then there are two seemingly identical triggers that will trigger some code on page load.
Doesn't seem like a very useful piece of code. Is there some larger portion that might shed some light on this?

In JS, You can declare a function and automatically call it afterwards:
( function Test() { alert('test'); } )();

The parentheses define a temporary scope. It is sometimes useful to do so in JavaScript. There are a number of examples and further explanation in John Resig's excellent guide to learning advanced JavaScript:
http://ejohn.org/apps/learn/#57

Related

Anonymous functions syntax in jQuery

I have read lots of articles regarding jQuery and its syntax. However I have not fully understood its syntax and I would really like to get a better and deeper understanding of it.
Many articles fail to point out the simple syntax rules (and what they are necessary for).
As of right now I am experiencing a syntax-understanding-problem:
my HTML:
<body>
jQuery.com
jQuery.com
jQuery.com
<!-- JQUERY -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
(function ($) {
// EXAMPLE 1
$("a").each(function () {
console.log(this.title);
});
})(jQuery); // ... everything works fine.
(function ($) {
// EXAMPLE 2
$("a").each(function () {
console.log(this.title);
});
}); // ... missing (jQuery). Why isn't this working?
$(function () { // ... notice the $ at the beginning.
// EXAMPLE 3
$("a").each(function () {
console.log(this.title);
});
}); // ... missing (jQuery). Why IS this working?
// EXAMPLE 4
$("a").each(function () {
console.log(this.title);
}); // ... everything works fine.
</script>
</body>
I will clarify how I understand the code, and I would absolutely appreciate if you answer me in a very basic manner. Please do point out all my misunderstandings!
My Understanding and Questions so far:
Example 1: I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it. I pass it the jQuery-Object (with ($) but I don't know why this is important at that point). From now on my function 'speaks' jQuery (it understands its syntax - I am assuming). At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.
Example 2: I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?
Example 3: Now I STARTED my Javascript-function with the $ and I assume that from now on my whole function is WRAPPED inside a jQuery object. Inside this jQuery-object my function understands jQuery syntax. At the end NO (jQuery) is needed.
Example 4: Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.
My Question basically is:
In Example 1, why is that ($) at the beginning AND the (jQuery) at the end necessary? What is the purpose?
I would really appreciate longer answers where I can get a deeper understanding of "reading jQuery syntax correctly" and speaking about jQuery syntax and what it requires. Thanks.
I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it.
Not quite. You create a function expression.
function () { }
You then follow it with () which calls it a moment later.
You could have done it like this:
var myfunction = function ($) { ... };
myfunction(jQuery);
I pass it the jQuery-Object (with ($) but I don't know why this is important at that point).
No. You are defining a function. It accepts a single argument, the value of which gets assigned to a local variable called $.
From now on my function 'speaks' jQuery (it understands its syntax - I am assuming).
Syntax belongs to JavaScript, not jQuery.
At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.
You are passing the jQuery object for the first time. It is the argument you are passing to the function when you call it. The value of jQuery (the jQuery object) is assigned to the local $ variable.
This is used for two purposes:
It lets you use the $ variable without worrying about it being overwritten by Prototype JS, Mootools, or any of the other libraries that thought it was a good idea to use something as generic as $ as a variable name.
It lets you have local variables that won't pollute the global scope.
I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?
The () are important because without them you won't call the function.
The jQuery is important because otherwise $ would be undefined within the function.
Now I STARTED my Javascript-function with the $
Here you are calling the function $() with your function expression as the argument.
$ is a horribly overloaded function that does many different things depending on what type of argument you pass it.
If you pass it a function, then it will assign that function as a document ready event handler.
When the DOM has finished loading, the event will fire and the function will be called.
Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.
Yes
First off, there is no "jQuery syntax". jQuery is a library, written in JavaScript, so the syntax is JavaScript.
Example 1: I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it. I pass it the jQuery-Object (with ($) but I don't know why this is important at that point). From now on my function 'speaks' jQuery (it understands its syntax - I am assuming). At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.
You seem to know how functions and arguments work. So look at your code:
(function ($) {
// EXAMPLE 1
$("a").each(function () {
console.log(this.title);
});
})(jQuery);
You define an anonymous function that takes one argument: a variable named $, which you use in the statement $("a"). Then you call your anonymous function and pass it the jQuery object, so inside the function, $ === jQuery.
Example 2: I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?
Without the () at the end, you're not even calling your function. You just define it and then lose it since you're not assigning it to a variable.
If you put just (), it won't work either because the function argument $ would be undefined and override the global $ (window.$).
However, if you declared the function just as function(), I think it would work because $ would then refer to window.$.
Example 3: Now I STARTED my Javascript-function with the $ and I assume that from now on my whole function is WRAPPED inside a jQuery object. Inside this jQuery-object my function understands jQuery syntax. At the end NO (jQuery) is needed.
Now you call $ as a function with one argument: your anonymous function.
Example 4: Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.
Yes you do build a function, and you pass it as argument to the each() function of the object that $("a") returns.
My Question basically is:
In Example 1, why is that ($) at the beginning AND the (jQuery) at the end necessary? What is the purpose?
What's the purpose of arguments to functions?
But what you don't seem to understand: $ is just a variable (or a function if you want, but in JS functions are variables).
The solution to your problem comes down to understanding closures within JavaScript ... and not so much jQuery - jQuery is just using closures.
With a closure you can scope the content that is within and also pass arguments to that closure for use within.
For your example 2, if you pass in jQuery to the closure it would work fine.
Like:
(function ($)
{
$("a").each(function () {
console.log(this.title);
});
})(jQuery); // arguments passed in here
Becuase you do not pass in jQuery at the end then the argument $ is undefined and therefore cannot be called in the case of $('a'). When written the way I have changed it jQuery is assigned to the $ argument, which is available to the code which is inside the closure.
Similarly for your example 3, you are not passing in jQuery and you also have no variable $ within your closure so it will not work. Note that you could change it to be like (illustrative purposes only):
(function (thisIsJquery)
{
thisIsJquery("a").each(function () {
console.log(this.title);
});
})(jQuery);
Now jQuery is assigned to the argument thisIsJquery and it is available within the closure.
As for your exmaple 4, $ is being used within the closure it was defined in (and not another closure inside that) so it is readily available for use.
Closures are an excellent way to hide implementation and provide a way to make things private in JavaScript.
Further reading:
http://www.w3schools.com/js/js_function_closures.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
I'll only focus on what's not working. The following snippet:
(function ($) {
$("a").each(function () {
console.log(this.title);
});
}) // not calling function
First of all, you're not calling the function. So, anything inside it will not run. So, you might think that by adding () at last, might solve it.
But that's not all!
Because $ refers to jQuery, outside the snippet. But since you're including a named parameter as $ and not passing anything to it, the $ inside the snippet shadows the one outside. And since it's not assigned any value, it is undefined. So you'll end up with
undefined is not a function
To prove it, adding ($) will work, as now, the named parameter $ refers to the $ which points to jQuery.

Jquery function?

Before writing any jquery they always recommend us using
$( document ).ready(function() {});
and place all our code within this function, but I noticed certain tutorial use this instead
(function($){})(jQuery)
and
(function($){}(jQuery));
what is the difference actually?
$( document ).ready(function() { YOUR CODE });
1. This code wraps YOUR CODE in jQuery's on document ready handler. This makes sure all the HTML is loaded before you start running your script. Also, since YOUR CODE is part of an anonymous function (a closure), this keeps your global scope clean.
...
$(function(){ YOUR CODE });
2. This is the same thing as #1, just using shorthand.
...
(function($){ YOUR CODE })(jQuery)
3. This does not wrap anything in an on ready handler, so it'll run immediately, without regard to what HTML has been loaded so far. However, it does wrap YOUR CODE in an anonymous function, where you'll be able to reference the jQuery object with $.
...
(function($){ YOUR CODE }(jQuery));
4. This is the same thing as #3.
$(document).ready(function() {//when document is read
And
$(function() {
are the same thing, the second is just short hand
You can also do
$(window).load(function() {
//The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images.
(function($){})(jQuery)
is an Self-Executing Anonymous Function
So basically it’s an anonymous function that lets jQuery play nicely with other javascript libraries that might have $ variable/function. Also if you notice, all jQuery plugins code is wrapped in this anonymous function.
The first one is executing the function as soon as the document is ready while the others are IIFE's that ensures jQuery can be accessed via it's alias sign $ within that function :
var $ = 'other plugin';
(function($){
alert($); // jQuery here
})(jQuery);
The first one makes the method run on document ready. Read more here.
(function($){/*Your code*/})(jQuery)
The last two encapsulate variable / function declarations in your code to a local scope, that gets as a prameter the jQuery object. This approach is used for not littering the global scope with declarations,ie localizing variables.
The difference between the last two is just that the first one delimits function with an extra set of parentheses, to make it visually more clear.
Basically this is how modules are constructed in javascript and making sure one block of code doesn't affect the other.
For more information here's a good article about js development patterns.
Example:
var f = function (str) {
window.alert(str);
};
var name = "John Doe";
f();
Functionally is the same as
(function (w) {
var f = function (str) {
w.alert(str);
};
var name = "John Doe";
f();
})(window);
And as you can see, the first one creates variables in the global scope, that might affect other scripts, while the second one does everything locally.
Moreover in the second example I did rename the reference to window, and made it available for the method through w. The same happens in your example as well.
Imagine having two js libraries that both use the alias shorthand $. You wouldn't know in your code where, which gets referenced. While on the other hand jQuery always references the jQuery library. And in your case the last two methods just make sure that $ is just a renamed jQuery object, and not anything else coming from another library.

Declaring functions inside anonymous function

I am looking at code that appears to be declaring a function that would need to be called to run. This function is being declared within an anonymous function. Doesn't this mean that the function will be inaccessible to anything outside of this block?
(function () {
var _d = vjo.dsf.EventDispatcher;
var _r = vjo.Registry;
function $1(p0) {
return function (event) {
return this.onSubmit(p0, event);
};
};
})();
Why would someone do this?
I am not sure of the purpose/relevance of $ in this code.
"Doesn't this mean that the function will be inaccessible to anything outside of this block?"
Yes it does.
"Why would someone do this?"
Usually because it contains code for internal use only, though in your example, the function is never invoked.
"I am not of the purpose/relevance of "$" in this code."
No relevance. Just another valid variable character.
The example you posted shows a common pattern of writing "modules" in javascript, although one that has an error. $1 is never invoked and is private, which means it might as well not exist. However, in a valid example, there would be additional code that would call $1 and possibly other functions. Then, when this code was included, the whole thing would evaluate, yet the global namespace would not get polluted with the declarations.

Troubles with (function(){})() [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 8 years ago.
So far I've learned the benefits of using this function (is it wrapping?)
So, it almost acts like namespaces.
Suppose we have:
( function() {
function foo(){
alert(true);
}
foo(); //alerts true
})();
( function() {
function foo(){ //the same title of the function as above
alert("another call of foo");
}
foo(); //alerts, ok.
})();
Also I've noticed it can access public vars, like this:
var __foo__ = 'bar';
( function() {
alert(__foo__); //alerts bar
})();
I have several questions regarding this approach
What I've tried:
Use Bing for tutorials (I' found them, but many of them don't answer my questions)
Play with passing objects into the body
Find the answer here
But, I'm still beating my head against the wall
So the questions are:
I've seen people pass objects as params, but when DOES it make sense?
For example, what does it mean?
( function(window) {
})(document);
I saw smth like this in Jquery UI Lib
( function($) {
//some code of widget goes here
})(Jquery);
This makes inner code visible outside the function, right? (not sure) Why, this is because
we can access the object (say we have "modal" widget), simply by calling it,
like:
$(function(){
$("#some_div").modal(); //here it's object the we got from the function
});
And the second question is: How does it work.
I've seen people pass objects as params, but when DOES it make sense? For example, what does it mean?
( function(window) {
})(document);
The language does not treat parameters to immediately called functions differently than parameters to other functions.
It makes sense to use a parameter whenever you want a local name in your function body for an input. In this case it's a bit confusing since window and document are likely to be confused.
( function($) {
//some code of widget goes here
})(Jquery);
This makes inner code visible outside the function, right? (not sure) Why, this is because we can access the object (say we have "modal" widget), simply by calling it,
No. It does not by itself make any code visible outside the widget. It's just a parameter definition which provides a new&local name for a global variable.
What makes inner code visible outside is attaching it to an external object as in
$.exportedProperty = localVariable;
which is a common convention in jQuery code.
There are mainly 2 purposes of passing in the window and document objects such as seen below
(function(window, document){
// code
}(window, document);
Javascript can access local variables faster than global variables. This pattern in effect makes the names window and document local variables rather than global, thus making your script slightly faster.
Making these names local variables has another benefit: minifiers can rename them. So if you minify the above script, the local version of window might get renamed to a and document might get renamed to b, thus making the minified script smaller. If you were to reference them as globals, these renamings are impossible because that would break your script.
For more info, checkout these awesome videos
http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/
on your first question, I dont think you seen window and document but something more like:
(function(doc) {
var fubar = doc.getElementById("fubar"); // === document.getElementById("fubar")
})(document);
you have a self-invoking function (or closure) with arguments like any function:
var b = function(str) { alert(str); }
b('hi there') //alert('hi there');
the same thing is it with the code above, but we are just calling the method at once we created it.
the other code you have:
( function($) {
//some code of widget goes here
})(Jquery);
is to reserve the $variable inside the metod to refer to the jQuery object, this is very handy if you have more frameworks or replaced the $ object with something else, everything inside that method with an $ will refer to the jQuery object and nothing else(if you don´t replace it inside your code).
the code:
$(function(){
$("#some_div").modal(); //here it's object the we got from the function
});
is calling jQuery and its a shortcut for $(document).ready
it will call the method:
function(){
$("#some_div").modal(); //here it's object the we got from the function
}
as soon as the DOM is ready
The pattern is called a closure. It makes sense to use when a module or function:
wants to avoid polluting globally-scoped variables
wants to avoid use globally-scoped variables and avoid other code polluting them
For an example of each, first take this pattern:
(function(window) {
// ...
})(window);
Everything inside the closure will be able to use window as if it were a local variable.
Next, take the same pattern using the JQuery symbol:
(function($) {
// ...
})($);
If you have some code that relies on a symbol/namespace like $, but another module reassigns that, it can screw up your code. Using this pattern avoids this by allowing you to inject the symbol into a closure.
Whenever you pass an argument to that wrapping function it's so that you won't mess up with any other libraries or global variables that may be present in your application.
For example as you may know jQuery uses $ as a symbol for calling itself, and you may also have another library, that will also use $ for calling itselt, under this condition you may have trouble referencing your libraries. so you would solve it like this:
(function($){
// here you're accessing jQuery's functions
$('#anything').css('color','red');
})(jQuery);
(function($){
// and in here you would be accessing the other library
$.('#anything').method();
})(otherLibrary);
This is specially useful when you're making jQuery or any other kind of library plugins.
What it does is allow you to use the $ variable inside your function in place of the jQuery variable, even if the $ variable is defined as something else outside your function.
As an example, if you're using both jQuery and Prototype, you can use jQuery.noConflict() to ensure that Prototype's $ is still accessible in the global namespace, but inside your own function you can use $ to refer to jQuery.

small question on js syntax

I saw this syntax many times but I couldn't find a way to google it properly, I hope I can get some help here:
<script>
(function(){
//code goes here
})();
</script>
Why is the function keyword wrapped in the parenthesis? What does it do and what is this called?
In js, the syntax:
function() { //code }
defines an anonymous function. You can store this into a variable and call it:
var a = function() { //code };
a();
or if you don't want to bother assigning it you can do it in one step.
(function() { //code })();
the parenthesis are necessary because:
function() { //code }();
is not proper syntax.
This syntax is useful in certain situations to help memory management as well as change variable names. For example in javascript you have a jQuery object, but most people refer to it as $. But sometimes $ is used as some other variable instead of the jQuery object. To fix this, you can wrap your code in:
(function($) { // code that uses $ })(jQuery);
That way you can use the dollar sign and not have to worry whether or not it actually points to the jQuery object or not.
It is called an anonymous function that is being called immediately.
// defining and calling a named function
function x() { /* do something */ }
x();
// defining an anonymous function (usually to assign it to a variable)
var x = function () { /* do something */ };
x();
// defining and calling an anonymous function in one step
(function () { /* do something */ })();
Most often the last pattern is used as part of creating a closure.
You can google (or search on Stack Overflow) JavaScript anonymous function or closure
Some links:
http://en.wikipedia.org/wiki/Anonymous_function
http://jibbering.com/faq/notes/closures/
See Bob Fincheimers answer for an explaination of what it means.
It is used to wrap a bunch of functions and variables that the programmer doesn't want to be visible from the outside - that's good when you're using libraries or so, you don't want them to block many function names for internal stuff.

Categories

Resources