CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   DOM and JSON scripting (http://www.codingforums.com/forumdisplay.php?f=15)
-   -   global vs local-Please help to understand the principle (http://www.codingforums.com/showthread.php?t=286644)

chickentulip 01-29-2013 04:16 PM

global vs local-Please help to understand the principle
 
I was wondering if you could take a look at the code below that i have found in a book:

Code:

var a = 123;

function f() {
alert(a);
var a = 1;
alert(a);
}

f();

When the function f is called, the first alert shows underfined and the second shows 1. The books says this happens because "inside the function the local scope is more important than the global scope. So a local variable overwrites any global variable with the same name. At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space."

I have a problem understanding how it works. My question, is at what stage, the local variable overwrites a global variable? At the stage of defining the function or calling it? I just want to have a clear picture in my heads what is going on. thank you very much.

niralsoni 01-29-2013 04:48 PM

Refer to - http://www.codeproject.com/Articles/...otchas#noblock

felgall 01-29-2013 06:34 PM

All the local variables referenced within a function are declared as local variables before any of the code in the function runs. Effectively it is as if you had one var at the top of the function with all of the variables declared using var within the function as a comma separated list after it - as that is where all the declarations run it makes your code easier to read if you actually put the declarations there.

With modern strict JavaScript all variables need to be declared and your script will fail to run if you try to use one that isn't declared. Also by wrapping ALL of your code in anonymous functions you can avoid using global variables almost completely - with only one or two being needed to provide access to shared libraries.

A strict and unobtrusive version of that code would look like this:

Code:

(function() {"use strict";
var a = 123;

function f() {
var a; // declaration moved to where it is actually run
alert(a); // used just to demonstrate that at this point the local variable is declared but undefined
a = 1;
alert(a);
}

f();
})();

With that code the first variable set to 123 is local to the outer function and so will not clash with any similarly named variable in any other script you add to the same web page.

Philip M 01-30-2013 07:48 AM

It is very poor practice to use two variables with the same name, even if one is local and the other global. There is absolutely no reason for doing this. Also, it is best to devise variable names which are meaningful and indicate the content - not meaningless "a", but (say) "firstnumber" or "customernumber".

sunfighter 01-30-2013 04:22 PM

I have always used "window" to get my globals. Your code would therefore be:
Code:

var a = 123;

function f() {
alert(window.a);
var a = 1;
alert(a);
}

f();


felgall 01-30-2013 06:20 PM

Quote:

Originally Posted by sunfighter (Post 1309782)
I have always used "window" to get my globals.

Your JavaScript shouldn't be using many global variables at all. For example if you are using jQuery then the only global variable you should have in your code is jQuery. Would you really reference that as window.jQuery rather than simply as JQuery throughout your code?

With the OP's code written properly neither variable would be global and trying to reference the nonexistant window.a variable would stop the script from running at all.

Code:

(function() {"use strict";
var a = 123;

function f() {
var a; // declaration moved to where it is actually run
alert(window.a); // this would prevent the script running as no such variable exists
a = 1;
alert(a);
}

f();
})();


sunfighter 01-30-2013 07:22 PM

I really don't know where your coming from Stephen. Why would anyone use window.jQuery? I personally use the $ sign. I'm sure you do also.
and I never used
Code:

function f() {
var a; // declaration moved to where it is actually run
alert(window.a);

and never would.

It was not about the "use strict" statement that you introduced. It was just showing that window.variable can be used to get a global variable into a local variable with little work like:
globalgal being a global variable and:
Code:

function f(){
var localelady = window.globalgal;

allows you access it with little to no sweat.

felgall 01-30-2013 09:47 PM

Quote:

Originally Posted by sunfighter (Post 1309835)
I really don't know where your coming from Stephen. Why would anyone use window.jQuery? I personally use the $ sign. .

So now you are contradicting yourself. You said with global variables you always use window. on the front of the name and now you have contradicted that and said that for the one global variable you need when using JQuery you use $. So in fact you don't use window. on the front of the only global variable that you ought to have when using JQuery.

When using JQuery - jQuery should be the only global JavaScript variable in the page. There is no need to have $ defined as well. After all you only need to reference the global variable twice and one of those is to turn off $.

Code:

jQuery.noConflict();
(function($) {
// your jQuery code goes here
})(jQuery);


rnd me 01-30-2013 10:29 PM

Quote:

Originally Posted by felgall (Post 1309863)
When using JQuery $ should be the only global JavaScript variable in the page.

nope, jQuery is defined also.


@sunfighter:
often some jerk/library decides to use "$", and then adds jQuery to the site. using window.jQuery ensures that you don't mis-apply the unexpected $ var as though it were jQuery.


quick aside:
i like to use self instead of window to hit globals so that the code can run in WebWorker threads if needed and it's less to type.

rnd me 01-30-2013 10:35 PM

think of local and global variable names much like you would a person's name. If you are talking around the water cooler and you say "barack is doing a good job", the other folks will likely assume you mean barack obama. If however, your CEO is named barack, they will probably assume the more local barack, and think of their boss. In that case, you would have to say barack obama to differentiate between the global barack (obama) and the local barack (your boss).

Javascript is the same way; it assumes that you always mean those closest to you unless instructed otherwise.

sunfighter 01-31-2013 03:51 AM

Quote:

Originally Posted by felgall (Post 1309863)
So now you are contradicting yourself. You said with global variables you always use window. on the front of the name .....

No, I said:
Quote:

I have always used "window" to get my globals.
Post #5 and it's not been edited.
What I never said was:
Quote:

I use jquery.
I fact, I try not to. 117Kb for the min library is a lot of overhead for a few effects. Now that is not saying I don't or wont use jquery, it says I try not to.

felgall 01-31-2013 06:14 AM

Just noticed and corrected an error in what I said before - of course jQuery is the only global variable that you would use if using that library. After all you only need to reference it twice and the first of those is to turn off the global $ variable so it can be reused. You wouldn't bother referencing window.jQuery and of course $ is not a global variable once the first statement runs and so if you use jQuery you need exactly two global references to jQuery - there is no possibility of confusion between global and local variables because those are the only two references to the variable.

Quote:

Originally Posted by sunfighter (Post 1309912)
Now that is not saying I don't or wont use jquery, it says I try not to.

So what library do you use that results in your needing to have global variables? Only if a library creates more than one global variable and doesn't provide an option to turn the extras off or if you use multiple libraries do you end up with more than one global variable in your web page.

The point I have been trying to make is that UNLESS you use a library like JQuery where you need one or two global variables to access the library, there is no reason to have any global variables at all.

If you don't have a library to access then simply wrap all your code inside an anonymous function and then none of the variables will be global any more - and so will be unable to clash with similarly named variables in other scripts.

Personally I just name my global variables differently to the variables I use locally - so $A, $B, $D, $E, and $O are the main globals that my scripts reference because those are the objects that I have created that provide most of the common functionality that my scripts use. Adding window. on the front of the variable names in those instances seems somewhat redundant - particularly as I usually pass whichever ones are being used as parameters into the anonymous function so that there isn't anywhere that calls them globally other than as a parameter to a self executing anonymous function. Each global variable gets referenced exactly one per script.

When each global variable is only referenced once in the standard wrapper around your code there is absolutely no point whatever in prefixing it with window. - the fact that it is being passed into your script as a parameter is sufficient to identify that it is global.

sunfighter 01-31-2013 06:21 PM

I agree with everything you said in the above post. I can not think of the last time I used a global with one exception and that maybe laughable but it's how I roll so to speak.

When I use ajax I have marcos that input JS code at the start of my <body> to make the ajax object. I set that as a global. Don't need to, but the macros are already set up.


All times are GMT +1. The time now is 03:32 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.