Checking if an attribute gets attached to $scope - javascript

This question really consists of two:
1 - Do functions create their own $scopes in javasript?
e.g.$scope.foo = function() {
$scope.bar = "Bar";
}
I ask this because in one such test that I'm trying to run I check to determine the existence of a variable on the scope, run a function and then recheck:
iit('getPatientFirstName should attach patientName to the scope', function() {
// Passes
expect(scope.patientName).toBeUndefined();
spyOn(scope,'getPatientFirstName').andCallThrough();
scope.getPatientFirstName(detailsBody);
// Fails
expect(scope.patientName)not.toBeUndefined();
});
// In the controller
$scope.getPatientFirstName = function (dataBody) {
$scope.patientName = dataBody.patientFirstName;
};
So this suggests that they may have their own scope? If this is the case can we test this?
2 - Is a valid alternative just to use an object that exists outside the function:
$scope.patientDetails = {
patientName: ''
};
$scope.getPatientFirstName = function (dataBody) {
$scope.patientDetails.patientName = dataBody.patientFirstName;
};
Thanks
EDIT
Considering the two answers has raised another question - is a variable (attribute or object) considered global if its attached to the $scope? It can be accessed in any function in that controller but as far as being called in a completely different controller - yes it can?
Confirm/Deny anyone?
And it appears that assigning the variable to the $scope global is considered valid for the purposes of my test.

Regarding your first questions, no, functions do not create new $scopes by their own (note that we are talking about scopes and not closures, which are two different concepts).
In your example, the $scope.foo function creates a new bar property on the same $scope object where foo is defined. The final $scope object would look something like this:
$scope {
foo: function() {
$scope.bar = "Bar";
},
bar: "Bar"
}
The problem with your test may be related to the missing . before the not.
expect(scope.patientName).not.toBeUndefined();
Is a valid alternative just to use an object that exists outside the
function:
Yes, you can use an object that's defined outside the function.
If the object is on the same $scope object you will have no problems, just make sure it is defined before you run the function, otherwise you will get a $scope.patientDetails is not defined error.

I'll answer the question a little differently than where you are taking it. I hope it helps you to rethink your stategy.
1 - Do functions create their own $scopes in javasript?
They do create an own scope. But the surrounding scope is also available within the scope. So when you write a function within a function, the inner function can use all the variables of the outer function
Example
function foo() {
var a=5;
function bar() {
var b=4;
}
function hello() {
var c=3;
}
}
a is available for all the functions, foo, bar and hello.
b is not available for foo nor for hello.
c is not available for foo nor for bar.
2 - Is a valid alternative just to use an object that exists outside the function:
So, you should try to make an outer function; there you can declare variables that will be strictly contained within that outer function.
Any function you create within this outer function can make use of that outer scope.
Variables that are global should be avoided if possible.
An example: jQuery.
jQuery has 1 variable that is global: var jQuery ( You can also access it by its alias $ ).
The variables that jQuery uses will not be in conflict with any variables you use.
And anything you want from jQuery, you will have to go through $ (or jQuery)

Related

Hardcore javascript module scope

The problem : I want to iterate over my list of functions, and modify them in place, using code like:
for(var funcProperty in scope) {
scope['_'+funcProperty] = scope[funcProperty];
scope[funcProperty] = wrapFunctionInTryCatchBlock(scope['_'+funcProperty]);
}
I want to do this without explicitly having to go through all my functions, and add them to some object, thereby creating the required scope. I don't want to do that because then all the functions, which call each other, will have to have their names modified and lengthened to become:
funcName becomes scopeObject.funcName : annoying.
I could do this quite easily if my functions were in the global object, i.e, Window, however I don't want to pollute the global namespace, so I have put them in a module, like so:
var MyModule = (function() {
function privateFunc1(...) {...}
function privateFunc2(...) {...}
var public_api = {
coolName : privateFunc1
};
return public_api;
}());
However, I can see and find no way to access the scope object that exists in the immediately executed function call the return value of which is assigned to MyModule.
I tried doing this, from within MyModule:
console.log(this)
To see if we did have access to the scope, somehow, yet, of course, it turned out that this referred to Window.
My question is really: What is the scope object that the methods in MyModule private scope are assigned to, since it is not the global object, and it does exist, since all the functions have implicit access to it. Is there any way I as a JavaScript programmer can explicitly access the scope object and enumerate its properties or is that FORBIDDEN?
I'm not going to rush to accept this as the answer, but I have found one possible solution that I am happy with.
Definition of "happy with" in this case is : minimal extra work, almost no changes to existing code.
The solution
We modify the module code like so:
// $ = wrapFunctionInTryCatchBlock
function $(fun) {
return function() {
try {
return fun.apply(this,arguments);
} catch(err) {
console.log("Error",err,err.stack);
}
};
}
var MyModule = (function() {
var privateFun1 = $(privateFun1(...){...});
var privateFun2 = $(privateFun2(...){...});
var public_api = {
coolName : privateFun1
};
return public_api;
}());
Why this works
We get the desired code modification (function wrapping), essentially in place since the variables assigned to function expressions have exactly the same scope as the original named functions themselves.
A VIM regex to help
I also created a VIM regex to help with this, at least the assignment line anyway:
s/function \(\w\+\)\(.\+\)$/var \1 = $(function \1\2/g

Javascript Function Declaration Options

I've seen experts using below to declare a function:
(function () {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
//etc
}());
e.g.
https://github.com/douglascrockford/JSON-js/blob/master/json.js
Could someone help me understand when should we use above pattern and how do we make use of it?
Thanks.
Well, since ECMA6 hasn't arrived yet, functions are about the best way to create scopes in JS. If you wrap a variable declaration of sorts in an IIFE (Immediately Invoked Function Expression), that variable will not be created globally. Same goes for function declarations.
If you're given the seemingly daunting task of clearing a script of all global variables, all you need to do is wrap the entire script in a simple (function(){/*script here*/}());, and no globals are created, lest they are implied globals, but that's just a lazy fix. This pattern is sooo much more powerful.
I have explained the use of IIFE in more detail both here, here and here
The basic JS function call live-cycle sort of works like this:
f();//call function
||
====> inside function, some vars are created, along with the arguments object
These reside in an internal scope object
==> function returns, scope object (all vars and args) are GC'ed
Like all objects in JS, an object is flagged for GC (Garbage Collection) as soon as that object is not referenced anymore. But consider the following:
var foo = (function()
{
var localFoo = {bar:undefined};
return function(get, set)
{
if (set === undefined)
{
return localFoo[get];
}
return (localFoo[get] = set);
}
}());
When the IIFE returns, foo is assigned its return value, which is another function. Now localFoo was declared in the scope of the IIFE, and there is no way to get to that object directly. At first glance you might expect localFoo to be GC'ed.
But hold on, the function that is being returned (and assigned to foo still references that object, so it can't be gc'ed. In other words: the scope object outlives the function call, and a closure is created.
The localFoo object, then, will not be GC'ed until the variable foo either goes out of scope or is reassigned another value and all references to the returned function are lost.
Take a look at one of the linked answers (the one with the diagrams), In that answer there's a link to an article, from where I stole the images I used. That should clear things up for you, if this hasn't already.
An IIFE can return nothing, but expose its scope regardless:
var foo = {};
(function(obj)
{
//obj references foo here
var localFoo = {};
obj.property = 'I am set in a different scope';
obj.getLocal = function()
{
return localFoo;
};
}(foo));
This IIFE returns nothing (implied undefined), yet console.log(foo.getLocal()) will log the empty object literal. foo itself will also be assigned property. But wait, I can do you one better. Assume foo has been passed through the code above once over:
var bar = foo.getLocal();
bar.newProperty = 'I was added using the bar reference';
bar.getLocal = function()
{
return this;
};
console.log(foo.getLocal().newProperty === bar.newProperty);
console.log(bar ==== foo.getLocal());
console.log(bar.getLocal() === foo.getLocal().getLocal());
//and so on
What will this log? Indeed, it'll log true time and time again. Objects are never copied in JS, their references are copied, but the object is always the same. Change it once in some scope, and those changes will be shared across all references (logically).
This is just to show you that closures can be difficult to get your head round at first, but this also shows how powerful they can be: you can pass an object through various IIFE's, each time setting a new method that has access to its own, unique scope that other methdods can't get to.
Note
Closers aren't all that easy for the JS engines to Garbage Collect, but lately, that's not that big of an issue anymore.
Also take your time to google these terms:
the module pattern in JavaScript Some reasons WHY we use it
closures in JavaScript Second hit
JavaScript function scope First hit
JavaScript function context The dreaded this reference
IIFE's can be named functions, too, but then the only place where you can reference that function is inside that function's scope:
(function init (obj)
{
//obj references foo here
var localFoo = {};
obj.property = 'I am set in a different scope';
obj.getLocal = function()
{
return localFoo;
};
if (!this.wrap)
{//only assign wrap if wrap/init wasn't called from a wrapped object (IE foo)
obj.wrap = init;
}
}(foo));
var fooLocal = foo.getLocal();
//assign all but factory methods to fooLocal:
foo.wrap(fooLocal);
console.log(fooLocal.getLocal());//circular reference, though
console.log(init);//undefined, the function name is not global, because it's an expression
This is just a basic example of how you can usre closures to create wrapper objects...
Well the above pattern is called the immediate function. This function do 3 things:-
The result of this code is an expression that does all of the following in a single statement:
Creates a function instance
Executes the function
Discards the function (as there are no longer any references to it after the statement
has ended)
This is used by the JS developers for creating a variables and functions without polluting the global space as it creates it's own private scope for vars and functions.
In the above example the function f(){} is in the private scope of the immediate function, you can't invoke this function at global or window scope.
Browser-based JavaScript only has two scopes available: Global and Function. This means that any variables you create are in the global scope or confined to the scope of the function that you are currently in.
Sometimes, often during initialization, you need a bunch of variables that you only need once. Putting them in the global scope isn't appropriate bit you don't want a special function to do it.
Enter, the immediate function. This is a function that is defined and then immediately called. That's what you are seeing in Crockford's (and others') code. It can be anonymous or named, without defeating the purpose of avoiding polluting the global scope because the name of the function will be local to the function body.
It provides a scope for containing your variables without leaving a function lying around. Keeps things clean.

Is it better to declare a function with or without var? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between using var and not using var in JavaScript
There are two ways I've seen people declare functions in javascript. Either:
foo = function()
{
//Do stuff
}
or
var foo = function()
{
//Do stuff
}
I'm new to javascript, and would like to know if there is a real difference between the two. Is one better to use than the other, or does it depend on the situation?
AFAIK, if you do not state var then your function will be assigned to the global scope (same scope level as the window object), however if you declare it as var it will be contained within its parent scope.
EDIT: to clarify after the response from Tomalak, the function will belong to its parent scope, however if the parent scope is a function which is executed, after execution of the enclosing function, any functions declared without var will be accessible within the global context.
There are two ways:
Declaring it in a variable
Using the default function declaration
In your case, you're trying to declare it in a variable. Declaring variables (whether function or not) start with the var syntax.
var foo = function() { }; // please note that semicolon (;)
When defining a function normally:
function foo() { }
So, again, in your case, the var is required, unless you pre-define it:
var foo;
foo = function() { };
Edit: As James stated, if you wish to define it in the global scope you can discard the var keyword. But to be honest it's still a better practise to predefine the variable if you wish to define it on another scope level.
It's better to declare with var, otherwise you may be affecting any other var within the global scope. Check for example this question for more information: What is the scope of variables in JavaScript?

Why is this function wrapped in parentheses, followed by parentheses? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 9 years ago.
I see this all the time in javascript sources but i've never really found out the real reason this construct is used. Why is this needed?
(function() {
//stuff
})();
Why is this written like this? Why not just use stuff by itself and not in a function?
EDIT: i know this is defining an anonymous function and then calling it, but why?
This defines a function closure
This is used to create a function closure with private functionality and variables that aren't globally visible.
Consider the following code:
(function(){
var test = true;
})();
variable test is not visible anywhere else but within the function closure where it's defined.
What is a closure anyway?
Function closures make it possible for various scripts not to interfere with each other even though they define similarly named variables or private functions. Those privates are visible and accessible only within closure itself and not outside of it.
Check this code and read comments along with it:
// public part
var publicVar = 111;
var publicFunc = function(value) { alert(value); };
var publicObject = {
// no functions whatsoever
};
// closure part
(function(pubObj){
// private variables and functions
var closureVar = 222;
var closureFunc = function(value){
// call public func
publicFunc(value);
// alert private variable
alert(closureVar);
};
// add function to public object that accesses private functionality
pubObj.alertValues = closureFunc;
// mind the missing "var" which makes it a public variable
anotherPublic = 333;
})(publicObject);
// alert 111 & alert 222
publicObject.alertValues(publicVar);
// try to access varaibles
alert(publicVar); // alert 111
alert(anotherPublic); // alert 333
alert(typeof(closureVar)); // alert "undefined"
Here's a JSFiddle running code that displays data as indicated by comments in the upper code.
What it actually does?
As you already know this
creates a function:
function() { ... }
and immediately executes it:
(func)();
this function may or may not accept additional parameters.
jQuery plugins are usually defined this way, by defining a function with one parameter that plugin manipulates within:
(function(paramName){ ... })(jQuery);
But the main idea is still the same: define a function closure with private definitions that can't directly be used outside of it.
That construct is known as a self-executing anonymous function, which is actually not a very good name for it, here is what happens (and why the name is not a good one). This:
function abc() {
//stuff
}
Defines a function called abc, if we wanted an anonymous function (which is a very common pattern in javascript), it would be something along the lines of:
function() {
//stuff
}
But, if you have this you either need to associate it with a variable so you can call it (which would make it not-so-anonymous) or you need to execute it straight away. We can try to execute it straight away by doing this:
function() {
//stuff
}();
But this won't work as it will give you a syntax error. The reason you get a syntax error is as follows. When you create a function with a name (such as abc above), that name becomes a reference to a function expression, you can then execute the expression by putting () after the name e.g.: abc(). The act of declaring a function does not create an expression, the function declaration is infact a statement rather than an expression. Essentially, expression are executable and statements are not (as you may have guessed). So in order to execute an anonymous function you need to tell the parser that it is an expression rather than a statement. One way of doing this (not the only way, but it has become convention), is to wrap your anonymous function in a set of () and so you get your construct:
(function() {
//stuff
})();
An anonymous function which is immediately executed (you can see how the name of the construct is a little off since it's not really an anonymous function that executes itself but is rather an anonymous function that is executed straight away).
Ok, so why is all this useful, one reason is the fact that it lets you stop your code from polluting the global namespace. Because functions in javascript have their own scope any variable inside a function is not visible globally, so if we could somehow write all our code inside a function the global scope would be safe, well our self-executing anonymous function allows us to do just that. Let me borrow an example from John Resig's old book:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
All our variables and functions are written within our self-executing anonymous function, our code is executed in the first place because it is inside a self-executing anonymous function. And due to the fact that javascript allows closures, i.e. essentially allows functions to access variables that are defined in an outer function, we can pretty much write whatever code we like inside the self-executing anonymous function and everything will still work as expected.
But wait there is still more :). This construct allows us to solve a problem that sometimes occurs when using closures in javascript. I will once again let John Resig explain, I quote:
Remember that closures allow you to reference variables that exist
within the parent function. However, it does not provide the value of
the variable at the time it is created; it provides the last value of
the variable within the parent function. The most common issue under
which you’ll see this occur is during a for loop. There is one
variable being used as the iterator (e.g., i). Inside of the for loop,
new functions are being created that utilize the closure to reference
the iterator again. The problem is that by the time the new closured
functions are called, they will reference the last value of the
iterator (i.e., the last position in an array), not the value that you
would expect. Listing 2-16 shows an example of using anonymous
functions to induce scope, to create an instance where expected
closure is possible.
// An element with an ID of main
var obj = document.getElementById("main");
// An array of items to bind to
var items = [ "click", "keypress" ];
// Iterate through each of the items
for ( var i = 0; i < items.length; i++ ) {
// Use a self-executed anonymous function to induce scope
(function(){
// Remember the value within this scope
var item = items[i];
// Bind a function to the element
obj[ "on" + item ] = function() {
// item refers to a parent variable that has been successfully
// scoped within the context of this for loop
alert( "Thanks for your " + item );
};
})();
}
Essentially what all of that means is this, people often write naive javascript code like this (this is the naive version of the loop from above):
for ( var i = 0; i < items.length; i++ ) {
var item = items[i];
// Bind a function to the elment
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[i] );
};
}
The functions we create within the loop are closures, but unfortunately they will lock in the last value of i from the enclosing scope (in this case it will probably be 2 which is gonna cause trouble). What we likely want is for each function we create within the loop to lock in the value of i at the time we create it. This is where our self-executing anonymous function comes in, here is a similar but perhaps easier to understand way of rewriting that loop:
for ( var i = 0; i < items.length; i++ ) {
(function(index){
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[index] );
};
})(i);
}
Because we invoke our anonymous function on every iteration, the parameter we pass in is locked in to the value it was at the time it was passed in, so all the functions we create within the loop will work as expected.
There you go, two good reasons to use the self-executing anonymous function construct and why it actually works in the first place.
It's used to define an anonymous function and then call it. I haven't tried but my best guess for why there are parens around the block is because JavaScript needs them to understand the function call.
It's useful if you want to define a one-off function in place and then immediately call it. The difference between using the anonymous function and just writing the code out is scope. All the variables in the anonymous function will go out of scope when the function's over with (unless the vars are told otherwise, of course). This can be used to keep the global or enclosing namespace clean, to use less memory long-term, or to get some "privacy".
It is an "anonymous self executing function" or "immediately-invoked-function-expression". Nice explanation from Ben Alman here.
I use the pattern when creating namespaces
var APP = {};
(function(context){
})(APP);
Such a construct is useful when you want to make a closure - a construct helps create a private "room" for variables inaccessible from outside. See more in this chapter of "JavaScript: the good parts" book:
http://books.google.com/books?id=PXa2bby0oQ0C&pg=PA37&lpg=PA37&dq=crockford+closure+called+immediately&source=bl&ots=HIlku8x4jL&sig=-T-T0jTmf7_p_6twzaCq5_5aj3A&hl=lv&ei=lSa5TaXeDMyRswa874nrAw&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBUQ6AEwAA#v=onepage&q&f=false
In the example shown on top of page 38, you see that the variable "status" is hidden within a closure and cannot be accessed anyway else than calling the get_status() method.
I'm not sure if this question is answered already, so apologies if I'm just repeating stuff.
In JavaScript, only functions introduce new scope. By wrapping your code in an immediate function, all variables you define exist only in this or lower scope, but not in global scope.
So this is a good way to not pollute the global scope.
There should be only a few global variables. Remember that every global is a property of the window object, which already has a lot of properties by default. Introducing a new scope also avoids collisions with default properties of the window object.

What is the purpose of an anonymous JavaScript function wrapped in parentheses? [duplicate]

(function() {})() and its jQuery-specific cousin (function($) {})(jQuery) pop up all the time in Javascript code.
How do these constructs work, and what problems do they solve?
Examples appreciated
With the increasing popularity of JavaScript frameworks, the $ sign was used in many different occasions. So, to alleviate possible clashes, you can use those constructs:
(function ($){
// Your code using $ here.
})(jQuery);
Specifically, that's an anonymous function declaration which gets executed immediately passing the main jQuery object as parameter. Inside that function, you can use $ to refer to that object, without worrying about other frameworks being in scope as well.
This is a technique used to limit variable scope; it's the only way to prevent variables from polluting the global namespace.
var bar = 1; // bar is now part of the global namespace
alert(bar);
(function () {
var foo = 1; // foo has function scope
alert(foo);
// code to be executed goes here
})();
1) It defines an anonymous function and executes it straight away.
2) It's usually done so as not to pollute the global namespace with unwanted code.
3) You need to expose some methods from it, anything declared inside will be "private", for example:
MyLib = (function(){
// other private stuff here
return {
init: function(){
}
};
})();
Or, alternatively:
MyLib = {};
(function({
MyLib.foo = function(){
}
}));
The point is, there are many ways you can use it, but the result stays the same.
It's just an anonymous function that is called immediately. You could first create the function and then call it, and you get the same effect:
(function(){ ... })();
works as:
temp = function(){ ... };
temp();
You can also do the same with a named function:
function temp() { ... }
temp();
The code that you call jQuery-specific is only that in the sense that you use the jQuery object in it. It's just an anonymous function with a parameter, that is called immediately.
You can do the same thing in two steps, and you can do it with any parameters you like:
temp = function(answer){ ... };
temp(42);
The problem that this solves is that it creates a closuse for the code in the function. You can declare variables in it without polluting the global namespace, thus reducing the risk of conflicts when using one script along with another.
In the specific case for jQuery you use it in compatibility mode where it doesn't declare the name $ as an alias for jQuery. By sending in the jQuery object into the closure and naming the parameter $ you can still use the same syntax as without compatibility mode.
It explains here that your first construct provides scope for variables.
Variables are scoped at the function level in javascript. This is different to what you might be used to in a language like C# or Java where the variables are scoped to the block. What this means is if you declare a variable inside a loop or an if statement, it will be available to the entire function.
If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:
(function() {
var myProperty = "hello world";
alert(myProperty);
})();
alert(typeof(myProperty)); // undefined
Another reason to do this is to remove any confusion over which framework's $ operator you are using. To force jQuery, for instance, you can do:
;(function($){
... your jQuery code here...
})(jQuery);
By passing in the $ operator as a parameter and invoking it on jQuery, the $ operator within the function is locked to jQuery even if you have other frameworks loaded.
Another use for this construct is to "capture" the values of local variables that will be used in a closure. For example:
for (var i = 0; i < 3; i++) {
$("#button"+i).click(function() {
alert(i);
});
}
The above code will make all three buttons pop up "3". On the other hand:
for (var i = 0; i < 3; i++) {
(function(i) {
$("#button"+i).click(function() {
alert(i);
});
})(i);
}
This will make the three buttons pop up "0", "1", and "2" as expected.
The reason for this is that a closure keeps a reference to its enclosing stack frame, which holds the current values of its variables. If those variables change before the closure executes, then the closure will see only the latest values, not the values as they were at the time the closure was created. By wrapping the closure creation inside another function as in the second example above, the current value of the variable i is saved in the stack frame of the anonymous function.
This is considered a closure. It means the code contained will run within its own lexical scope. This means you can define new variables and functions and they won't collide with the namespace used in code outside of the closure.
var i = 0;
alert("The magic number is " + i);
(function() {
var i = 99;
alert("The magic number inside the closure is " + i);
})();
alert("The magic number is still " + i);
This will generate three popups, demonstrating that the i in the closure does not alter the pre-existing variable of the same name:
The magic number is 0
The magic number inside the closure is 99
The magic number is still 0
They are often used in jQuery plugins. As explained in the jQuery Plugins Authoring Guide all variables declared inside { } are private and are not visible to the outside which allows for better encapsulation.
As others have said, they both define anonymous functions that are invoked immediately. I generally wrap my JavaScript class declarations in this structure in order to create a static private scope for the class. I can then place constant data, static methods, event handlers, or anything else in that scope and it will only be visible to instances of the class:
// Declare a namespace object.
window.MyLibrary = {};
// Wrap class declaration to create a private static scope.
(function() {
var incrementingID = 0;
function somePrivateStaticMethod() {
// ...
}
// Declare the MyObject class under the MyLibrary namespace.
MyLibrary.MyObject = function() {
this.id = incrementingID++;
};
// ...MyObject's prototype declaration goes here, etc...
MyLibrary.MyObject.prototype = {
memberMethod: function() {
// Do some stuff
// Maybe call a static private method!
somePrivateStaticMethod();
}
};
})();
In this example, the MyObject class is assigned to the MyLibrary namespace, so it is accessible. incrementingID and somePrivateStaticMethod() are not directly accessible outside of the anonymous function scope.
That is basically to namespace your JavaScript code.
For example, you can place any variables or functions within there, and from the outside, they don't exist in that scope. So when you encapsulate everything in there, you don't have to worry about clashes.
The () at the end means to self invoke. You can also add an argument there that will become the argument of your anonymous function. I do this with jQuery often, and you can see why...
(function($) {
// Now I can use $, but it won't affect any other library like Prototype
})(jQuery);
Evan Trimboli covers the rest in his answer.
It's a self-invoking function. Kind of like shorthand for writing
function DoSomeStuff($)
{
}
DoSomeStuff(jQuery);
What the above code is doing is creating an anonymous function on line 1, and then calling it on line 3 with 0 arguments. This effectively encapsulates all functions and variables defined within that library, because all of the functions will be accessible only inside that anonymous function.
This is good practice, and the reasoning behind it is to avoid polluting the global namespace with variables and functions, which could be clobbered by other pieces of Javascript throughout the site.
To clarify how the function is called, consider the simple example:
If you have this single line of Javascript included, it will invoke automatically without explicitly calling it:
alert('hello');
So, take that idea, and apply it to this example:
(function() {
alert('hello')
//anything I define in here is scoped to this function only
}) (); //here, the anonymous function is invoked
The end result is similar, because the anonymous function is invoked just like the previous example.
Because the good code answers are already taken :) I'll throw in a suggestion to watch some John Resig videos video 1 , video 2 (inventor of jQuery & master at JavaScript).
Some really good insights and answers provided in the videos.
That is what I happened to be doing at the moment when I saw your question.
function(){ // some code here }
is the way to define an anonymous function in javascript. They can give you the ability to execute a function in the context of another function (where you might not have that ability otherwise).

Categories

Resources