I have this code in jQuery..
$(document).ready(function(){
var fieldCounter = 0; ...
I have a jQuery function that increments this value.
This works, but I can't access this value on the page from a non-jQuery function? The reverse is also true, if I scope it in JavaScript e.g.
<script type="text/javascript">
var fieldCounter = 0;
I can access it from javascript but jQuery can't view it?
I'm probably doing something really dumb?
It has nothing to do with jQuery, but all with Javascript scope.
$(document).ready(function() {
var fieldCounter = 0;
});
fieldCounter is declared inside a function. Since Javascript has function scope, the variable is not visible outside the function.
BTW, jQuery is Javascript, they play by the same rules, they're not two different technologies.
Exhaustive answers can be found here: What is the scope of variables in JavaScript?
jQuery is not magic. It is a JavaScript library. Your issue is that you're defining a local variable inside a function. Due to the way JavaScript lexical scoping works, you can't access it outside that function (with the exception of closures, which does not apply here).
Most likely, you just want:
$(document).ready(function(){
fieldCounter = 0;
That will make it a global variable.
Edit: Note that using a namespace and/or declaring the global variable is cleaner, but not required.
Your problem in the first case is scope. By putting the var init inside a function declaration, you've scoped it to access inside that function.
Something else is going on in the second case; more code would be necessary to see what.
The global scope in Javascript is window. That means that when you declare variables directly in <script> tags, you can get them back by asking for window.variableName.
A common way to resolve these kinds of scoping issues is to create a namespace framework. If you do it right you can call myNamespace.subNamespace.variable and have full confidence that because it's explicitly scoped to window, you can get it back no matter where you are.
Remember that jQuery is built in Javascript. There's nothing special about it.
JavaScript has function scope.
var count = 8;
var myfunction = function() {
var newCount = count + 1;
};
alert(newCount); // undefined
it's because of the scope of javascript... try to read this
Variables declared inside jQuery code block will have local scope.If you need to access a variable both in local javascript function as well as jQuery code block then declare the variable at global level. Sample Code snippet :-
<script type="text/javascript" language="javascript">
var increment = 0;
$(document).ready(function() {
$("#button2").click(function() {
increment = increment + 1;
alert(increment);
});
});
function ClickMe() {
increment = increment + 1;
alert(increment);
}
</script>
Related
This is my config in test.js:
var still;
jQuery(function(still){
still = 5;
});
console.log(still);
i want to show on console the variable 'still' (5), but is show to me 'undefined' !
can any1 help me :) !
Thanks
check this code. remove still from function as argument
var still;
jQuery(function(){
still = 5;
});
console.log(still);
This is because your global still variable has been hidden by function's argument with the same name. Try this:
var still;
jQuery(function(stillTheArgument){
still = 5;
});
console.log(still);
Please, reconsider your code as global variables are often not very good idea.
To prevent clogging the global namespace, alternatively you could pass the variable via immediately invoked function expression like so:
The variable still will be available within the scope of the outer function.
(function($, still) {
$(function() {
alert(still);
});
})(jQuery, "STILL");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
You are overriding the current global variable with your function variable as it currently stands.
as charlietfl told consol statement executed first. and at that time value of still is undefined.
try initializing still like this, no need of onReady handler
var still=5;
console.log(still);
Where do I need to place a snippet of JavaScript code that initializes a variable that must be visible to all code executed with the page? (For example, event handlers on elements will need to access this variable).
The only way to not have a global variable is to use the var keyword in the scope of a function. Anything else is a global variable.
(function() {
var local = 5;
})();
It doesn't matter if the function is a literal or function definition, it has to be some type of function.
Global variable examples:
1:
var global = 5;
The above is not in a function scope, therefore global even if var is used.
2.
(function() {
global = 5;
})();
In the above, no var was used, so it becomes an implied global.
3.
function foo(){}
foo was not defined inside of another function or assigned to a object key so its globally accessible.
4.
(function() {
var local = global = 5;
})();
When doing multiple assignments with var, only the first variable becomes local... so global is a global variable and equates to 5.
5.
window.foo = 5;
Prefixing window. is an explicit way of defining a global variable in the context of a browser.
6.
this.x = 5;
By default in browsers, this points to the DOMWindow unless you're in a method that's attached to an object which is not window. It's the same as #5. Note that if you use a method like XMLHttpRequest, the context is of the window.
7.
with ( window ) { name = 'john'; }
If you use the with statement and you dont reference an object that already has a property, a global variable is defined. It's best to avoid using the with keyword in general.
Conclusion:
Personally, I would keep my code in an anonymous function scope, and only explicitly declare globals when I need to.
(function() {
var governor = 'Schwarzenegger',
state = 'California';
window.president = 'Obama';
})();
In the above, I define governor and state variables and they are local to my function. I want to explicitly define president as a global variable. This way, I'm not confused about which variables I defined as globals or not, because I explicitly prefix them with window..
You can do it out of any function, or in a function without using the 'var' keyword. Assign it before any other scripts (very top of the page, likely) so the scripts can read the value.
You can also place it in an included JS file, but putting it right on the page is usually more usable as you can see the global values easily, and they can be modified for each page by the server-side code. Also try to prevent assigning global variables in the body, it may make confussions and will be harder to read.
<head>
<script>
var numberOfDucks = 1000; // Global
function some_function() {
// numberOfDucks is accessible here
alert (numberOfDucks);
// until you mask it by defining a local variable using the 'var' keyword
var myLocal = 0; // is a local
anotherGlobal = 0; // is a global
}
</script>
<script>
// potentially some other script
</script>
<script src="even_more_script.js">
</head>
Defining a global in a function (implied-global) is not a good idea because it will make a lot of confussion.
you could place that variable at the beginning of the page (in the global scope if you HAD to make it visible everywhere) but I suggest two things
1) since you have to open a script block, avoid to declare it inside the body of your page since scripts block rendering. So put it just before </head>
2) avoid to create a simple var but use a namespace instead so you reduce risks of identifier collision
<script>
var YOUR_APP_NS = {};
YOUR_APP_NS.yourvar = ....
</script>
this is a good practice in order to not polluting the global scope. If you need several public var in this way you could just write
YOUR_APP_NS.yourvar1 = ....
YOUR_APP_NS.yourvar2 = ....
YOUR_APP_NS.yourvarN = ....
but the global var is still 1
Declare the variable outwith of any of your functions, that way it becomes a global variable.
Here's an example of a global variable. The first function uses the global but the second function uses a local variable with the same name which masks the global.
var globalVar = 1;
function testFunc1 () {
globalVar = 2; //Updates the global variable
}
function testFunc2 () {
var globalVar = 5; // This variable masks the global and only updates within the scope of this function
globalVar = 3;
}
Also, you mentioned that the snippet must initialise the global before any other reference. For this I would suggest you place your script block or reference to your javascript file before any other javascript references in your element as possible. If you have other javascript files which are going to rely on the global variable then you may wish to ensure they do not load until the rest of the page has loaded first using the defer attribute. See the following:
<script src="dependant.js" type="text/javascript" defer="defer"></script>
Another option is to dynamically add your dependant scripts after your initial script has loaded. You can do this using something like jQuery as follows:
$(window).load( function() {
$.getScript('dependant.js');
});
<head>
<script>
var b = 0;
</script>
<script src="...">
</head>
<body>
...
</body>
(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).
(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).
I am learning YUI and have occasionally seen this idiom:
<script>
(function x(){ do abcxyz})();
</script>
Why do they create a function just to invoke it?
Why not just write:
<script>
do abcxyz
</script>
For example see here.
They're taking advantage of closures.
A short explanation: Since JS uses function-level scoping, you can do a bunch of actions within a function and have it remain in that scope. This is useful for invoking code that doesn't mess with the global namespace. It also allows one to make private variables - if you declare a variable inside of an anonymous function and execute it immediately, only other code inside of the anonymous function can access that variable.
For example, suppose I want to make a global unique id generator. One might do code like this:
var counter = 0;
var genId = function()
{
counter = counter + 1;
return counter;
}
However, now anyone can mess with counter, and I've now polluted the global namespace with two variables (counter and genId).
Instead, I could use a anonymous function to generate my counter function:
var genId = function()
{
var counter = 0;
var genIdImpl = function()
{
counter = counter + 1;
return counter;
}
return genIdImpl;
}();
Now, I only have one variable in the global namespace, which is advantageous. More importantly, the counter variable is now safe from being modified - it only exists in the anonymous function's scope, and so only the function genIdImpl (which was defined in the same scope) can access it.
It looks like in YUI's example code, they just want to execute code that doesn't pollute the global namespace at all.
They want to avoid namespace collisions, I'd guess. Seems as a good practice in JS.