When Closures, Loops, Function References, And Anonymous Functions Interact

Oct 16, 2010

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?

View 7 Replies


ADVERTISEMENT

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

View 5 Replies View Related

Closures / Object References And Private Methods

Aug 22, 2010

I have some confusion about the scripts below:

1) is getRule a local variable or global variable, as it has no var keyword, yet it is an inner function of Validation? So without var, I think global, but being an inner function, I think local. So I'm not sure which.

2) In this line of code: var rule = $.Validation.getRule(types[type]), getRule returns rules, which is just a local variable in Validation. I always see that you return functions, but how does returning a local variable that's just an object literal and not a function be able to return true or false? Now the value of rules is an object literal, and this object returns true or false. So we are basically allowed to use return keyword with local variables that are object literals and not functions?

3) In this line, is foo(age) being called, or is it just being assigned to bar OR is it being called and THEN assigned to bar: var bar = foo(age);

4) Now for the most confusing: age is obviously an object reference as opposed to a literal in the example. Does that make a difference in regards to closures?
Note that I read a number of books, including JavaScript Programmer Reference and Object Oriented JavaScript and jQuery cookbook, which compare primitives vs reference types and how primitive types store directly in memory whereas reference tpyes reference memory, so if one reference changes, they all change where primitive remains ingrained. But when assigning a function as a reference like this, how does that affect the object "age" when passed into bar?

Code:
(function($) {
/*Validation Singleton*/
var Validation = function() {
var rules = {
email : {
check: function(value) {
if(value)
return testPattern(value,".+@.+..+");
return true;
}, .....
$.Validation = new Validation();
})(jQuery);

Code:
function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + tmp);
x.memb = x.memb ? x.memb + 1 : 1;
alert(x.memb);
}}
var age = new Number(2);
var bar = foo(age); // bar is now a closure referencing age.
bar(10);

View 3 Replies View Related

Anonymous Functions In Tag Attributes?

Jun 13, 2010

I'm not having any luck writing this:

Code:
<a onclick="function(e) {clicked(e, 1);}">hit me</a>

and don't have the option of defining the click event outside the <a> tag.

Is it possible to pass in the click event and an additional parameter to the clicked function?

View 4 Replies View Related

Binding Encapsulated Anonymous Functions Without Repetition

Nov 12, 2004

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:

if(typeof document.addEventListener != 'undefined')
{
document.addEventListener('click', someFunction, false);
}
else if(document.attachEvent != 'undefined')
{
document.attachEvent('onclick', someFunction);
}

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:

//identify supported method of adding encapsulated event listeners
etype = (typeof document.addEventListener != 'undefined') ? 'addEventListener' : (typeof document.attachEvent != 'undefined') ? 'attachEvent' : 'none'

//set event name prefix
eprefix = (etype == 'attachEvent' ? 'on' : '');

//if encapsulated event listening is not supported, don't continue
if(etype == 'none') { return; }

so anonymous functions are built like this:

element[etype](eprefix + 'event', function()
{
... code ...
}, false);

Even though attachEvent doesn't require a third argument, it's ignored, so this syntax works for all.

View 13 Replies View Related

Average From Loops Without Arrays Nor Functions?

Oct 26, 2011

I've now got to form an average of snowfall inputs, taken from looped prompts, however I'm not allowed to use arrays or functions...Almost every example I see uses arrays, such as this one here:http://www.codingforums.com/showthread.php?t=4313Is it possible to not use arrays to form the average? Please describe how to do this in general terms, as was highlighted in that link ^^^ I want to learn, not copy, although one can be derived from the other...What I haveso far, assume all vars have been announced.

for (var d=1; d<=numofinputs; d=d+1)
{
input = prompt("Enter a data input" + d)
}

View 4 Replies View Related

Creating A M*n Table Using Functions And For Loops?

Oct 16, 2011

Write a script to generate two random numbers for variable m and n, the values generated for the variables should range from 1 to 10. We want to make an m * n table (m rows and n columns) with the word Hello in each of its cells. Now define a function f with one parameter n that displays n columns of one row of the table (You need a for-loop). Call this function m times to display m rows of the table. For example if m = 6 and n = 4 we should get the following:

HelloHelloHelloHello
HelloHelloHelloHello
HelloHelloHelloHello

[code]....

(The above is supposed to be a table but did not copy fully)This was my attempt, although i really did not know how to attack this.

<script type="text/javascript">
function f(n)
{

[code]...

View 4 Replies View Related

JQuery :: Calling An Anonymous Function?

Feb 3, 2011

I have a problem with understanding jQuery. In my case I have this JS file with following content (see below). This is an anonymous function, isn't it? The problem is this line:

[Code]...

View 1 Replies View Related

Getting Return Value From Post Anonymous Function

Jan 8, 2011

I have been struggling with a form wizard all day. I'm using jquery stepy (form wizard) along with validation plugin. To cut a long story short, my first step is to get MySQL connection from form controls details. On submit ('next' button) a check is made on an empty hidden control ('hid').

rules: {
hid: {
required: function(){
return checkDBData();
},
messages: {
hid:
{required: 'SQL not available'},
...(etc)...

So, if the function checkDBData passes, false should be returned, so that the form can progress to the next step. If the connection details fail, true is returned so that an error msg is posted.

Here's the checkDBData function:
function checkDBData(){
var host = $('#mysql_host').val();
var username = $('#username').val();
var password = $('#password').val();
var dbname = $('#dbname').val();

$.post("install/sqlcheck.php",
{"host": host,"username": username, "password": password, "dbname": dbname},
function(msg){
if(msg.required == false){
return false;
}else{
return true;
}},
"json"
);
}

The return values don't find their way back to the rules. However, if I hard code false and true to the function...
function checkDBData(){
var host = $('#mysql_host').val();
var username = $('#username').val();
var password = $('#password').val();
var dbname = $('#dbname').val();

$.post("install/sqlcheck.php",
{"host": host,"username": username, "password": password, "dbname": dbname},
function(msg){
if(msg.required == false){
return false;
}else{
return true;
}},
"json"
);
return false; //or return true for testing purposes
}
This works. I assume it's due to the asynchronous nature of the ajax call.

View 2 Replies View Related

Creating Anonymous Function With Variable?

Mar 20, 2010

I'm having trouble with something that I can't explain outside of an example. Code:

Code:
$js_info_tabs = json_encode($valid_array);
$script = <<<JAVASCRIPT
<script type="text/javascript">//<![CDATA[
function changeTo(id) {

[Code]....

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.

View 1 Replies View Related

Giving AddEventListerner An Anonymous Function?

Nov 3, 2011

var name = "good";
load_image( name );
function load_image( name )

[code]....

I've tried giving addEventListerner an anonymous function

View 3 Replies View Related

Returning ResponseXML, Set Within An Anonymous Function, Only Once ReadyState = 4

Dec 4, 2006

I have several functions with code along the lines of:

var xmlDoc = requestXML("ajax.asp?SP=SelectRelatedTags&tag=" +
array[i]);

The requestXML() function includes the code:

var xmlDoc = null;
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xmlDoc = http_request.responseXML;
} else {
alert('There was a problem with the request.' +
http_request.status);
}}};
http_request.open('GET', url, true);
http_request.send(null);
return xmlDoc;

However, the last line (the return) executes before the readyState
reaches 4. How do I return the xmlDoc to the functions only once the
xmlDoc has been assigned? I tried putting the return statement in a
while loop with the condition that the readyState must = 4 - this
worked, but makes the browser popup a message saying the script is
slowing down the system.

View 1 Replies View Related

Passing Anonymous Function From SetTimeout() - IE Doesn't Like - FF Does

Jun 6, 2009

I did search the forums but couldn't seem to find anything on this specifically. I basically need to pass a key event and a 'name' to nameCheck() after 3 seconds. This works fine in Firefox but Internet Explorer gives the error: Member not found. I'm more of a PHP guy than a JS one

<input type="text" onkeyup="nameCheckTimer(this.value, event)" value="" />
function nameCheckTimer(name, evt) {
setTimeout(function(){return nameCheck(name,evt)}, 3000);
}
function nameCheck(name, evt) {
//need name and the key event to be available here. I have code to handle the key codes which works fine
}

View 6 Replies View Related

Passing 'this' To Anonymous Function In Event Listener

Jun 10, 2010

I'm working with nested functions and trying to pass a 'this' value to an anonymous being used in an assignment for an event listener.So, this should plop a button inside our DIV and when clicked I'd like it to run the alert-ding; unfortunately it seems to want to run the function as defined under the buttons object which doesn't work out too well.

View 3 Replies View Related

JQuery :: Pass Reference To An Object To Anonymous Function?

Aug 2, 2010

I would like to know how to pass in a reference of this to anonymous function so I can access parameters from anonymous. Here is my code:

[Code]...

View 2 Replies View Related

Create An Anonymous Function For Onchange Event Of File Field?

Feb 28, 2010

I am trying to create an anonymous function for onchange event of file field, so that when a file is selected, the covering text field gets that value. I know how to accomplish this by adding onchange="", but I'd prefer not do that. The code that I have almost works, except that the function in the for loop can't call on the "i" variable that the loop uses.

for( i = 0; i < source.length; i++) {
source[i].onchange = function() {
name[i].value = this.value;
}
}

View 3 Replies View Related

Function Won't Work With Loops?

Nov 28, 2010

We have created this function with loops and arrays Problem is the loops work only when I take out the function when the function is in place, nothing works, it is part of exercise

here is my code
title>Congressional Races</title>
<link href="results.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="votes.js"></script>
<script type="text/javascript">

[Code]...

View 5 Replies View Related

JQuery :: Related To Setting Global Variables From Anonymous Function (valid = False;)?

Oct 22, 2010

//<input type="text" id="s_field" value=""/>
var valid = true;
var div = $("#s_field");
$.post("index.php",{id: 6}, function (data){

[Code]..

When posting data, and getting response need to set valid to false - email is not valid.

1. in function it alerts valid is false
2. outside function it says valid is still true!

even i didn't wrote var valid = false;, but valid = false;I need to set Global "valid" variable to false.

View 1 Replies View Related

Accessing Class Member Using This Inside An Anonymous Function Call In A Class Method?

Mar 28, 2010

I'm using jquery to make it easy for AJAX calls.

So I create a class: function cMap(mapID){//vars and stuff}

I go and prototype a function: cMap.prototype.loadMap = function(){ //jquery AJAX call }

Now in the jquery $.ajax({...}); call, I use an anonymous function on the "success:" call: success: function(data){ this.member = data; }

My problem is that inside this anonymous function call I'm trying to call a class member of my cMap class to store the data in from the AJAX call, but it's out of scope. So the JS console in FF/Chrome throws errors about bad value/doesn't exist.

How can I access this class member from inside an anonymous function? Or at least what's a good way to go about doing all this?

View 2 Replies View Related

Still Not Getting Closures Right?

Nov 16, 2010

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.

View 6 Replies View Related

Variable Scope And Closures

Jul 23, 2005

Given the following working code:

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?

View 3 Replies View Related

Accessing Closures In SetTimeout?

Sep 20, 2011

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.

View 5 Replies View Related

Interact With An API But Struggling With XHR?

Jan 23, 2010

We're trying to interact with an API but struggling with XHR and how to send data/get response.

If you're able to help with a few small projects please get in touch with your typical hourly rate.

View 1 Replies View Related

Event Handling, DOM, Closures And Memory Leaks

Oct 18, 2006

I have a question regarding how to prevent memory leaks in Internet
Explorer when using closures. I already knew about the circular
reference problem, and until now was able to prevent memory leak
problems. But I needed to store DOM elements and can't solve it
anymore. So I search the group archive to see if I missed any
valuable information. I found some interesting articles, but somehow
could not apply it to my problem or I did not understand it fully.
In particular the articles that talked about setting variables to
NULL seemed as an easy solution, but I think I didn't understand it,
because it didn't seem to work.

So, let me explain my problem in more detail. I am working on some
very dynamic and complex page. It uses AJAX (XMLHttpRequest) to alter
different parts of the page. This already disqualifies the finalize
method solution to cleanup memory leak problems. I use several
"component classes" to do the work of creating DOM elements in some
container element and provide an easy to use interface for
manipulation the content. For example I can call
component.setBackgroundColor("red")
and the component takes care of changing the style on the correct
DOM element that is encapsulated in the component. In reality the
component uses more complex interface method, but I hope you
get the picture of why I do this.

Let me show you some example code:

function MyComponent()
{
var div;
var handler = null;

this.generate = function generate()
{
div = document.createElement("div");
div.onclick = MyComponent.createClickHandler(this);
// normally more elements are created here
return div;
}

this.setBackgroundColor = function setBackgroundColor(value)
{
div.style.backgroundColor = value;
}

this.getHandler = function getHandler()
{
return handler;
}

this.setHandler = function setHandler(value)
{
handler = value;
}

}

MyComponent.createClickHandler = function createClickHandler(component)
{
return function(event)
{
var handler = component.getHandler();
if (handler != null)
handler(event);
}
}

This "component class" can be used like this:

var container = document.getElementById("container");
var component = new MyComponent();
container.appendChild(component.generate());
....
component.setBackgroundColor("red");
component.setHandler(function(event) {alert("Stop touching me!")});

The problem, of course, is that this code will create a memory leak
in Internet Explorer. I need the component in the event handler to
get the handler dynamically, but the div is stored there too,
creating a circular reference.

One of the things I tried doing is making a DOMStorage "class" like
this:

function DOMStorage()
{
var map = new Object();

this.get = function get(id)
{
return map[id];
}

this.put = function put(id, obj)
{
map[id] = obj;
}

}

var storage = new DOMStorage(); //global

Instead of storing the div element directly in the component, I store
it under an id in the DOMStorage and use it to retrieve it later.
This actually prevented the memory leak. I don't really understand
why, because I still see a circular reference. Maybe Internet
Explorer does not count references in the global scope as a circular
reference? When I move the global storage to inside the container
object I get the memory leak again.

Unfortunately I am unable to use a global DOMStorage, because the
"component class" in instantiated many times, and they must all have
their seperate DOM elements.

Perhaps I have to generate unique ID's when I put a DOM element into
the global storage? It seems so over-the-top for something that works
perfectly fine in Firefox.

What are my alternatives?

View 2 Replies View Related

Use Prototype Or Closures Inside Functinon Definition?

Aug 7, 2009

Is it better to use prototype when declaring classes or is it better to use closures inside the definition, e.g.:

Code:

Code:

What are the main differences, and is one method preferred to the other?

As use of the class is the same, I can't really decide which to use.

View 2 Replies View Related

Stuck On Making Interact With Php?

Jul 10, 2009

Basically i have this code:

$(document).ready(function() {
$("form").hide();
$(".show").click(function() {[code]....

i am trying to make this code work on an array, ie. i have a for loop spinning out content from my data base and want to be able to to use this function on each paragraph of code individually.Of course i can make the loop increment useing i++ on this links and element ID for example, but i have no clue how to hand this in anyway to the jquery code.

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved