Variable Scope - Anonymous Functions And Self Invoking Closures
Jul 25, 2011
I think the last thing people seem to learn about in JavaScript when they're not coming from other programming languages is variable scope. Some even get all the way into AJAX without having learned about scope, and this is a time when it's really needed. Although the scope of JavaScript variables is non-complex by nature, it's something we should all get a full understanding for before we move too far.
Section 1: What is "scope"?
Section 2: The "var" keyword
Section 3: The "this" keyword
Section 4: Closures or "Anonymous functions and self-invoking closures
I am confused about the true difference between the two below examples.
first example:
// Demonstrating a problem with closures and loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array();
[code]....
Here we iterate through the length of myArray, assigning the current index of myArray to theItem variable. We declare closureArray 4 times as an anonymous function. The anonymous function in turn declares the predefined write() function, which is passed parameters. Since write() is in closureArray() a closure is created??? During each iteration, theItem is reassigned its value. The four closures reference this value. Since they reference this same value and since this value is reassigned ultimately to the value of the fourth index position, tHe time we execute closureArray later on, all four closures output the same string. This is because all four closures are within the same scope "the same environment" and therefore are referencing the same local variable, which has changed.
I have a couple of problems with this example:
1) I thought a closure is a function that is returned - the inner function is not returned above.
2) theItem is not even a local variable of the parent function (closureArray) - I thought in order for a closure to work, the inner function only accesses the local variables of the outer function, but in this case the local variable is defined OUTSIDE of the parent function.
3) the "the four closures are sharing the same environment." The thing is even in the second example, they are sharing the same environment.
Second example:
// A correct use of closures within loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array();
[code]....
Here we iterate over the length of myArray (4 times), assigning the index of myArray to theItem variable. We also return a function reference to the closureArray during each iteration (closureArray[i]), where i is index number so we assign 4 functon references. So when we iterate through myArray, we immediatelly call the writeItem() fucntion passing an argument of theItem at its current value. This returns a child anonymous function and when that child function is called, it will execute a block that calls the predefined write() method. We assign that returned anonymous function to the variable closureArray. Hence, closureArray holds a reference to that anonymous function. So closureArray during each iteration holds a reference to the anonymous function and we later call closureArray, which in turn calls the anonymous function, therefore calling the predefined write() function to output the local variable of the parent function. This outputs each distinct index of myArray.
This is because since we created the closure, when we call writeItem, passing theItem argument, since theItem is a local variable of the parent function of the closure, it is never destroyed when we later call closureArray (the reference to the child anonymous function)? Yet weren't we using a closure in the first example as well? So whey wasn't those variables preserved?
I don't think it has anything to do with assigning a returned anonymous function to closureArray. Even though an anonymous function creates a new memory position in the javascript engine, therefore not overwriting the other function references we create during the iteration, it's still referring to a local variable declared outside the reference. So if it's about the closure retaining value of parent's local variable even after exiting the parent function allowing for the current indexes to be preserved, then why did the closure in the first example fail to retain each index?
function attributes() { var attr1 = arguments[0] || '_' var attr2 = arguments[1] || '_' return ( function (el1, el2) { var value1 = el1[attr1] + el1[attr2]; var value2 = el2[attr1] + el2[attr2]; if (value1 > value2) return 1; else if (value1 < value2) return -1; else return 0; } ); }
var a = [ { a:'smith', b:'john' }, { a:'jones', b:'bob' }, { a:'smith', b:'jane' } ]; a.sort(attributes('a', 'b')); for (var i =0; i < a.length; i++) { document.write(a[i].a + ', ' + a[i].b + '<br>'); }
My question is, are attr1 and attr2 guaranteed to exist through the lifetime of a.sort(attributes('a', 'b'))?
As I understand it, the anonymous inner function reference I am returning is a property of attributes(). As such, when I return a reference to the anonymous inner function, the outer attributes() function must continue to exist (as must attr1 and att2) until there are no further references to the inner anonymous function.
As a result, there is no danger of attr1 or attr2 "disappearing" during the repeated calling of the anonymous inner function.
Is my explanation basically correct, or am I deluding myself and I'm just lucky that the garbage collector hasn't recovered attr1 or attr2 while the sort is still going on? In other words, is the behaviour I'm seeing consistent and predictable, or should I change my approach?
I am trying to convert some of my javascripts into a class and am running into difficulties which i think are related to variable scope.
Basically I have a constructor function for a calendarInput class that takes 4 parameters, the first is a reference name/number for this input. I also have some functions for importing my PHP classes into Javascript using AJAX (properties only. still trying to get methods working but that's another story!). The relevant function is called call_object_method(classname, methodname, createparams, methodparams, post, callbackfunction). This creates an instance of the specified PHP class using the parameters in createparams. It then calls the specified method using the parameters in methodparams. The result is passed back to the javascript function specified in the callbackfunction parameter (ie the value of xmlhttp.onreadystatechange is set to callbackfunction before xmlhttp.send() is called)
The function i am trying to fix is called show (x,y) which creates the html for the calendarInput and displays it at co-ordinates x, y.
this.showcallback = function() { alert(this); <!--//code to create html//--> }
}
I know i've cut out most of the innards of this. This is because I have already tested these functions and had the calendarInput working outside of a class, hence am pretty sure that this is ok (plus it runs to almost 1000 lines these days!!). My problem is that when I call the show method, the alert on the first line of the callback function returns the function showcallback instead of (as i was expecting) the instance of the calendarInput object. Whilst this kinda makes sense I can't figure out how to reference the Object instead. I have tried 'this.parent' but this returned undefined. I have tried changing the way i reference the callback function (ie the final parameter of call_object_method) but no joy.
I've recently started developing javascript using jQuery and so far I'm really enjoying it.Being a professional programmer (mainly C, C++, java and python) there is one thing that's been puzzling me regarding variable scope and unnamed function declarations. Let me exemplify:
------------------------ var sum = 0; $(xmlobj).find("item").each(function(){
I am using Ben Alman's JQuery resize plugin in order to obtain the varying computed width of an element when the window is resized (the element in question is a page wrapper that exhibits the expand-to-fit behavior of a block box, and it's computed width is obviously influenced by the resizing of the window. Essentially, what I need to be able to do, is to reference a variable that is defined in a .resize() function ('width_page') in a seperate .each() function.
[Code]...
I now understand that variables can't cross boundaries like in the example above, which leaves me a little stuck. I also understand that this is specific to the context of the .resize() function, and that it can't be taken out of it without using an element selector. Is there some way I can call the .resize() function in my .each() function?
Normally, if you want to bind encapsulated event listeners to an object you have to test for support and then call the same function in different ways, for example:
But there's code repetition there - okay not very much, because it's just a function call ... but what if you wanted to use an anonymous function ..? Well you can't - the code repetition would be unacceptible.
Except that I've though of a way :) It's really obvious actually .. but I'm posting this in the hope that others will go "wow, that's blindingly useful" as I did when I thought of it :thumbsup:
Here it is - it takes advantage of square-bracket notation to use a string reference to the supported method:
function agregar_row(){ for (i=0; i<10; i++){ row="row/" . i; if (document.getElementById(row).style.display=='none'){ document.getElementById(row).style.display='' i=11; } }}
This function is intended to make visible a row, just one by each time the function is called. the way im invoking "(row)" is wrong, i think...
I have the code this way in order to consolidate it since I would prefer to do that instead of checking the selected ID and manually checking against all possible IDs (which works flawlessly, it just takes up about 5x the lines and is not modular). What I have above also works, but there is one fatal flaw:
It seems like the anonymous function that is the onclick for each unselected element becomes "return changeTo(tab + '_id')", but I don't want it to be that. I want the argument to actually be what tab is instead of the variable.
What ends up happening is that after changeTo() is called for the first time, any element you click will result in the last element being the selected one, as if it's using the final value of tab as its return value.
This doesn't make any sense, though, since tab is local, and deleting it before the function exists doesn't work. Deleting elem at the end of the for loop doesn't work. I honestly don't understand what's going on or why it doesn't set the new onclick value correctly.
Basically I just want changeTo(tab + '_id'); to turn into changeTo('MYID_id'); instead, but it simply doesn't do that and I can't figure out a way how.
I would like to display the number 1 at first and then 2. but this code produces number 2 for both alerts. I was able to achieve what i wanted with "new" constructor when creating functions but this is not a good practice and after all i am passing these functions as an event handlers and it can't be done with "new" keyword because it is throwing error. I think there are some solutions with arrays e.g the x would be an array of numbers, but i don't like it. Am i missing something important?
I think I've had JavaScript variable scope figured out, can you please see if I've got it correctly?
* Variables can be local or global * When a variable is declared outside any function, it is global regardless of whether it's declared with or without "var" * When it is declared inside a function, if declared with "var", it's local, if not, it's global * A local variable that is declared inside a function is local to the whole function, regardless of where it is declared, e.g.:
function blah() { for(var i ... ) { var j ... }}
i and j will both be visible within blah() after their declaration. * the notion of "function" in this context also applies for this kind of construct:
var myHandler = { onClickDo: function() {
in the sense that whatever one declares inside onClickDo with "var" will only be visible inside onClickDo. What else, am I missing anything?
I've created a jQuery script that uses a switch statement. However, my experience with it, relative to variable scope, doesn't seem to follow the logic.According to the JavaScript/jQuery theory, a global variable was accessible (meaning read & write) throughtout any function within any script (one that page).However, apparently that theory wasn't completely true as it pertained to switch statements that contained variables. To illustrate my case in point, I've included a simplistic version of my code:
As shown, the variable "testVar" is not accessible from one case to the next case .Furthermore, to add insult to injury, I am seeing the same behavior within the conditional if else statement counterpart to the switch statement.
I have this web application where users are able to fill out and submit reports. The reports and scripts are part of a whole system, that is, they are used on a couple of different clients written in both vb and c#. This is the web-version of those clients.The scripting language is javascript and is executed using different script engines on the different systems. But for the web-version it is just executed in the browser.The different fields in the report can be accessed by typing:ID1.value. To get ID1 to apply for the input-field with id ID1 I had to in the initfunction of the page write a window["ID1"] = document.getElementById("ID1");
But my problem is when this element change. Cause in the report I have a special element that in the browser is translated to a table-element with a report-field in each cell.When I switch the current row, I need to update the window["ID1"] to equal the correct report field on the selected row. But when trying to access the new variable ID1 from a buttons onclick event it is undefined.<input type="text" id="test" onclick="alert(ID1.value);" />What I think happens is that when the page is first drawn the onclick event is created and as I understand, variables inside an event has the same value as when the event was created.
So if ID1.value was something when the page was created it will be the same when it is called even if the value of ID1 is different. And that seems to be the case. When I debug the page, before entering the event, ID1.value has the correct value while inside the event it is undefined and after the event it has the correct value. If I write window["ID1"] correct value is also shown.But a weird thing is that in another place in the code I had the same problem but instead of having the code inside the onclick event I first had a global function changeActiveRow and inside that I had an eval, eval(document.getElementById("ID1_script")) where ID1_script is a hidden element whos value is a script using ID1.value and that works.
I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me.
I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself.
I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time.
[code]how i can set context/scope for myStartAction so it can access (this.url) variable?console.log(dd.url) will work but i can't predict what name will object have (that depends on user) there might be more than one instance of myObject
a.) specify two parameters for the changeYear function: today and holiday.
function changeYear(today)(holiday){
b.) in the first line of the above function, use the getFullYear() date method to extract the 4-digit value from the today variable and store the value in a variable named year.
first line
c.) in the second line; use the setFullYear() date method to set the full year of the holiday date object to the value of the year variable.
second line
d.) in the third line, use a conditional operator on the year variable. The test condition is whether the value of the holiday date object is less than the today date object. If it is, this means that the event has already passed in the current year and the value of the year variable should be increased by 1.
third line
e.) in the fourth line of the function, again set the full year value of the holiday date object to the value of the year variable.
Arg, I'm losing hair. I'm having trouble understanding something extremely basic and important. I have functions who call functions who call functions.. but I'm having trouble doing anything useful with their results. I can't seem to "grab" them. They just get garbage collected. Scope is becoming my enemy.
This is also hard to explain because the code is modular, so stuff is calling stuff is calling stuff.
Everything happens inside a large Object.
[Code]...
Where do I have to go to understand basic Javascript things like getting values back out of a function? It's always the same problem I hit every time I use functions to figure out some value. It's always locked away.
If anyone happens to know of some place where one can practice with these things, that would be nice.Closures for morons? Functions for dummies? Something like that. I've got bookmarks of pages explaining functions and values and closures but I can't seem to take that over to what I want to do with them.
My problem is that every other turn I have to click either button twice to start the desired function. Say, I autoplay the images first and I want to shuffle them, I click shuffle and the autoplay stops working and I need to click shuffle again and then the shuffle runs. How can I make it clicked once and the function runs?
When writing JS, I try to encapsulate my code somehow. For instance, in the example below, I have a function ('testFunc') that's encapsulated within jQuery's document.ready callback function :
Code: $(function(){ var testFunc = function(x){ x++;[code]...
If I then start using JS's base timer functions like settimeout, I've always been unsure of how to access the 'testFunc' function. As I understand it, even if the timer functions are called inside the same function, as in...
Code: $(function(){ var testFunc = function(x){ x++; return x; }
var timer = setTimeout("testFunc", 100); });
... they will lose the scope of the jQuery callback - instead the timer functions will only be able to access objects in the global scope.
i'm having the following problem, normaly i work with html css and php but for this to work i need to make a litle javascript function and i'm still kinda new to it. so here is my problem.i'm making a search field where someone has to select some radiobuttons.first it has a selection out of 4 items and then a selection out of like 20 but how do i get the value from the first function in the second?in this case i would like to have the following in function showStreek:
xmlhttp.open("GET","test3.php?l="+land,true); this line should look like: xmlhttp.open("GET","test3.php?k="+kleur"l="+land,true);
I have been having trouble with forms and functions. On my wife's site I have some forms and some of them have radio buttons. My current radio button checker is cumbersome and it is time for something more elegant (some of you will say if it isn't broke don't fix it )
The new code is below:
Code:
Basically I want to pass into the function radio button values 1 & 2 denoted by firstChoice and secondChoice (eventually I want to also pass in the form name but 1 step at a time).
The buttons can have the value (names?) of pattern, chalkboard or kit. It is for a shopping cart (Mal's E-commerce) and this is part of the JS validation. I am using onsubmit to call the function viz.
HTML Code:
Seems ok (to me at least) but when I try to get it to work it throws up an error of
Code:
It stops at that point but undoubtably chalkboard would throw up the same error if it continued.
How would I define the variables in my function? Are they strings, integers, who cares? Where would I define them? Global or local?
Is the problem a matter of syntax e.g. if I put ' ' or " " around them would that suffice?