What is the purpose of using (function ($) {...}) [duplicate] - javascript

I am just starting out with writing jQuery plugins. I wrote three small plugins but I have been simply copying the line into all my plugins without actually knowing what it means. Can someone tell me a little more about these? Perhaps an explanation will come in handy someday when writing a framework :)
What does this do? (I know it extends jQuery somehow but is there anything else interesting to know about this)
(function($) {
})(jQuery);
What is the difference between the following two ways of writing a plugin:
Type 1:
(function($) {
$.fn.jPluginName = {
},
$.fn.jPluginName.defaults = {
}
})(jQuery);
Type 2:
(function($) {
$.jPluginName = {
}
})(jQuery);
Type 3:
(function($){
//Attach this new method to jQuery
$.fn.extend({
var defaults = {
}
var options = $.extend(defaults, options);
//This is where you write your plugin's name
pluginname: function() {
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
I could be way off here and maybe all mean the same thing. I am confused. In some cases, this doesn't seem to be working in a plugin that I was writing using Type 1. So far, Type 3 seems the most elegant to me but I'd like to know about the others as well.

Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. Let's break it down a little.
1. (
2. function(){}
3. )
4. ()
Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help
1. function(){ .. }
2. (1)
3. 2()
You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.
An example of how it would be used.
(function(doc){
doc.location = '/';
})(document);//This is passed into the function above
As for the other questions about the plugins:
Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.
Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.
Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.

At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. What this means is that you have defined a function and you are calling it immediately.
This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal).
A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). Hence:
(function($) {
...
})(jQuery);
Which means you're passing in a reference to the actual jQuery object, but it's known as $ within the scope of the function literal.
Type 1 isn't really a plugin. You're simply assigning an object literal to jQuery.fn. Typically you assign a function to jQuery.fn as plugins are usually just functions.
Type 2 is similar to Type 1; you aren't really creating a plugin here. You're simply adding an object literal to jQuery.fn.
Type 3 is a plugin, but it's not the best or easiest way to create one.
To understand more about this, take a look at this similar question and answer. Also, this page goes into some detail about authoring plugins.

A little help:
// an anonymous function
(function () { console.log('allo') });
// a self invoked anonymous function
(function () { console.log('allo') })();
// a self invoked anonymous function with a parameter called "$"
var jQuery = 'I\'m not jQuery.';
(function ($) { console.log($) })(jQuery);

Just small addition to explanation
This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:
(function($) {
// do something
})(jQuery);
this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $.

Actually, this example helped me to understand what does (function($) {})(jQuery); mean.
Consider this:
// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4
And now consider this:
jQuery is a variable holding jQuery object.
$ is a variable
name like any other (a, $b, a$b etc.) and it doesn't have any
special meaning like in PHP.
Knowing that we can take another look at our example:
var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4

Type 3, in order to work would have to look like this:
(function($){
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
'pluginname': function(_options) {
// Put defaults inline, no need for another variable...
var options = $.extend({
'defaults': "go here..."
}, _options);
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.

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.

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.

Calling a function in JavaScript without parentheses

Is there a way in JavaScript to call a function without parentheses?
For example in jQuery:
$('#wrap').text("asdf"); will work and so will $.ajax(ajaxOptions);
I'm mapping a function (class) to window.$ that has a set of functions I want to be able to call with or without parentheses. Like jQuery.
Here's a code example:
function Test(asdf) {
this.test = function(testVar) { return testVar + ' asdf'; }
}
And I map Test() to $:
window.$ = new Test();
I have to call the function (class) like this:
$('asfd').test('ASDF');
But I want to be able to call it like this:
$.test('asdf');
JavaScript is extremely flexible since objects are basically a map and can contain any number of key value pairs, where the value itself can be an object and thus you get nesting. Another interesting aspect of JavaScript is that functions are themselves first class objects, so in a key value pair, you can have a function as a value.
To get something like jQuery then becomes very simple. You start off with a function (constructor function, or class if you will),
function myFunction() {
// do some awesome web 2.0 stuff
}
Since myfunction is a function and also an object, so you attach key value pairs to it as well which is what jQuery does. To verify that myFunction is also an object, do an instanceof check:
myFunction instanceof Function; // true
myFunction instanceof Object; // true
So we can add properties to a function which could be simple values, or functions themselves.
// adding a simple property that holds a number
myFunction.firstPrime = 2;
// adding a function itself as a property to myFunction
myFunction.isPrime = function(number) {
// do some magic to determine if number is prime
};
But if that is not your question, and you really want to know if you can literally call a function without using parentheses, then the answer is yes, you can, using the additions in ECMAScript 5th ed.
Here's an example of calling a function without using parentheses using Object.defineProperty and defining it as a getter:
var o = {};
Object.defineProperty(o, "helloWorld", {
get: function() {
alert("hello world");
},
set: undefined
});
o.helloWorld; // will alert "hello world"
Try this example in Chrome or Safari, or Firefox nightly.
new
You can call a function using new. The twist is, within the function this becomes an object being constructed by the function instead of whatever it would normally be.
function test () { alert('it worked'); }
...
new test; // alerts "it worked"
call and apply
You can use call or apply to call a function indirectly. You'll still need parentheses (unless you use new), but you won't be directly invoking the function with parentheses.
function message() {return "Hello crazy world!"; }
Function.prototype.toString = function() { return this.call(this); };
alert(message);
The difference in those examples is that .text() is a function on jQuery objects (instances of them, wrappers of elements), it's on $.fn (jQuery's prototype shortcut) so it's specifically for jQuery objects.
$.ajaxSetup() is a method on the jQuery object/variable itself.
If you look at the API it's easy to tell which methods are where, the jQuery.something() methods are methods on the jQuery variable/object, not related to an element set, everything else that's just .something() are the methods to run against element sets (on jQuery object instances).
For what you want to do, yes it is possible, but it doesn't make much sense, for example:
$.myFuntion = $.fn.myFunction = function() { alert('hi'); };
You should place your methods where it makes sense, if it's for a set of elements, use $.fn.myFunction and this refers to the set of elements inside. If it's a static method unrelated to an element set place it outside separately or possibly at $.myFunction.
You can try something like this
var test = {
method1 : function(bar) {
// do stuff here
alert(bar);
},
method2 : function(bar) {
// do stuff here
alert(bar);
}
};
test.method1("foo");
test.method2("fooo");
You can make a function reference, but you won't be able to pass arguments:
function funky() { alert("Get down with it"); }
obj.onclick = funky;
Use template literals:
alert`WOW`
It is cleaner and shorter, without having to rely on jQuery, call, etc.

Anonymous Member Pattern Export/Import Function

I'm a bit confused. What is the purpose of the parameters when you initiate an anonymous member pattern designated below:
(function (<ParameterA>) {
})(<ParameterB>);
I understand that Parameter A is used to designate the scope of the function is this true?
Is ParameterB where you export the function?
Finally, I often see script indicating the following:
})(jQuery || myfunc);
Does that mean they're exporting these or returning these objects? And what's the point of using the two pipes (||); It a field goal thing?
Thanks in advance. Looking forward to interesting discussion.
Parameter A does not designate the scope of the function. The function's position determines the scope of the function. ParameterB is not where you export the function. In fact, the way this is set up, there is no pointer to the function anywhere which makes it an "anonymous function." In other words, as is, the function itself is un-exportable. Usually when you talk about exporting things, you're talking about exporting variables that you defined inside anonymous functions. For example, here I am exporting the function my_inner_function from an anonymous function.
(function (<ParameterA>) {
// export this function here.
window.my_inner_function = function() {
...
};
})(<ParameterB>);
Usually, the point of anonymous functions is that you have all kinds of variables that you don't want to export because you don't want to possibly muck with other code.
(function (<ParameterA>) {
// convert could be defined somewhere else too, so to be on the safe side
// I will hide it here in my anonymous function so nobody else can
// reference it.
var convert = function() {
...
};
})(<ParameterB>);
This is particularly important when you compress your Javascript and get function names like a and b.
(function (<ParameterA>) {
// So compressed!
var a = function() {
...
};
})(<ParameterB>);
(function () {
// Another compressed thing! Good thing these are hidden within anonymous
// functions, otherwise they'd conflict!
var a = function() {
...
};
})();
Now this
(function (<ParameterA>) {
})(<ParameterB>);
is the same thing as
// Assume ParameterB is defined somewhere out there.
(function () {
var ParameterA = ParameterB;
})();
Which gives you an idea why you'd use the parameters. You may find the parameter approach less confusing, or you may want to make it clear that you don't want to affect "by value" variables such as numbers and strings.
As others have pointed out, a || b is spoken as "a or b" and means "a if a evaluates to true, otherwise b, no matter what b is."
Edit
To answer your question, when you get to })(); the () causes the anonymous function to run. Remember that Javascript engines will first parse all code to make sure the syntax is correct, but won't actually evaluate/execute any code until it reaches that code. Hence, it's when the anonymous function runs that var ParameterA = ParameterB; gets evaluated. Here are some examples that hopefully help.
var ParameterB = "hello";
(function () {
var ParameterA = ParameterB;
// alerts "hello" because when this line is evaluated ParameterB is still
// "hello"
alert(ParameterA);
})(); // () here causes our anonymous function to execute
ParameterB = "world";
Now in this example, the function is no longer anonymous because it has
a pointer. However, it acts the same as the previous example.
var ParameterB = "hello";
var myFunction = function () {
var ParameterA = ParameterB;
// alerts "hello" because when this line is evaluated ParameterB is still
// "hello"
alert(ParameterA);
};
myFunction();
ParameterB = "world";
In this example, I change the order of the last 2 lines and get different
results.
var ParameterB = "hello";
var myFunction = function () {
var ParameterA = ParameterB;
// alerts "world" because when this line is evaluated ParameterB has
// already changed.
alert(ParameterA);
};
// notice that I moved this line to occur earlier.
ParameterB = "world";
myFunction();
The code block above executes an anonymous function immediately after declaring it.
ParameterA is a parameter to the anonymous function you are declaring
ParameterB is the value you are passing to ParameterA
So the function you declared will be executed immediately, passing ParameterB as the value for ParameterA.
The jQuery || myFunc block means this: use jQuery as the argument unless it is not defined, in which case use myFunc.
Edit:
This is often used when defining jQuery plugins to avoid conflicts with the $ variable if multiple javascript libraries are being used. So you would make your plugin definition a function that accepts $ as a parameter, which you would execute immediately, passing jQuery as the value to $.
Example (from jQuery docs):
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
The result of the above code block will be a plugin definition where you are guaranteed that $ will be an alias for jQuery.
For parts 1 and 2, ParameterA could be used to alias a nested hierarchy. (ie: YAHOO.util.Event passed in as ParameterB, can be used as "e" in ParameterA.) That way, inside the anonymous function, you wouldn't be typing out the full namespace path. [I know you're a jquery guy, but the yahoo namespace is longer, and illustrates the point better :)] Alternatively, you could just manually store the reference in a var inside the function.
the jquery || myFunc syntax is shorthand for "use jquery if it is truthy/available, or myFunc if it is not".
It's sort of like var toUse = jQuery !== undefined ? jQuery : myFunc;
This is because javascript allows falsy value evaluation without converting the objects fully to a boolean. ie: undefined is falsy, "" is falsy, null is falsy.
The alternative can be used to detect if a method or property is even available with &&.
ie: var grandParent = person && person.parent && person.parent.parent;
This will only be defined if the person has a parent, and their parent has a parent. Any failure along the && leading up to the last statement will result in grandParent being undefined.
Lastly, the parens around the || shortcut syntax are basically executing the function immediately after the declaration, passing the evaluated value into the anonymous function.
ie: (function(a, b) { return a + b; })(2,3)
Will immediately execute and return 5. In practice, this anonymous function execution could be used with the module pattern to establish a set of public methods which use private functions that themselves do not appear in the page's namespace. This is more in depth than your original question, but you can check out this article for more information: http://yuiblog.com/blog/2007/06/12/module-pattern/
ParameterA is referencing the value passed in at ParameterB. This:
(function (<ParameterA>) {
})(<ParameterB>);
Is sort of the same as this:
function test(<ParameterA>) {
}
test(<ParameterB>);
The difference is that this way you are using a closure to not have conflicting functions in the global namespace.
For the second part: the || work sort of like param = jQuery ? jQuery : myFunc. It passes in jQuery if it is defined, or myFunc if it isn't.
With your first part:
(function (<ParameterA>) {
})(<ParameterB>);
This means that the variable known as ParameterB outside the function will be known as ParameterA inside the function. This is known as a self-executing function, because the function is called as soon as it is defined. It means that you can use ParameterA inside the function without overriding a variable that exists outside the function.
For instance:
(function($){
})(jQuery);
This means that you can have $ as, for instance, Mootools outside the function and as jQuery inside it.
With your second part:
})(jQuery || myfunc);
This calls the function passing the jQuery variable if it exists, and myfunc if it does not. I don't quite know why you'd do this...

Need some help understanding this 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

Categories

Resources