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 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 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 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'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
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?
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.
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 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.
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 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);
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?
I'm trying to write an 'each' function for a JavaScript array that behaves like Ruby's Array#each. (It doesn't matter if you know Ruby to help with this question.)
My problem is the scope of 'this' inside the iterator callback. I would like it to be the same as the object that called the each() on the array. Right now I have to do that with a closure or an explicitly-passed 'this' scope. For example:
Array.prototype.each = function( inScope, inCallback ){ for ( var i=0,len=this.length; i<len; ++i ){ inCallback.call( inScope, this[ i ], i ); } }
Inside the each() function, arguments.callee.caller would give me a reference to the showInfo function object. What I am looking for is a way to access the scope of the 'this' receiver within that particular invocation of showInfo(), so that I can use it in place of inScope without having to pass 'this' each call.
In the method nextImage, I can't figure out how to access thumbs. It keeps coming back as undefined. (Using Firefox)
function runPortal(portal_number){ // there are multiple runPortals on each webpage this.portal = document.getElementById('portal'+portal_number); // represents the div that holds the images this.thumbs = this.portal.getElementsByTagName('a').length; // represents all the images within the div that will be rotated this.length = this.thumbs.length; // that's how many images will be rotated // Hide everything for (var j=0;j<this.thumbs.length;j++){ if (j==0) continue; // Don't hide the first one this.thumbs[j].childNodes[0].style.display = 'none' } this.nextImage = function (){ // there are a fixed number of images to rotate. Start over if (this.i >= this.length){ this.i = 0; } // One fades away, the next appears Effect.dglPuff(this.thumbs[this.last].childNodes[0], {duration:.6, from:.7}); Effect.Appear(this.thumbs[this.i].childNodes[0]);
// iterate to the next image for the next run this.last = this.i; this.i++; } // Set up the image rotator // here is where I started guessing // thumbs needs to belong to the object rotator, I guess.
this.rotator = new PeriodicalExecuter(this.nextImage, 4); // This object runs the function every 4 seconds this.rotator.portal = document.getElementById('portal'+portal_number); // represents the div that holds the images this.rotator.thumbs = this.rotator.portal.getElementsByTagName('a'); // represents all the images within the div that will be rotated this.rotator.length=this.length; // that's how many images will be rotated this.rotator.i=0; // the counter for what image we're one this.rotator.last=0; // the counter for the previous image
I have a script in which a function launched by a START button continuously calculates and writes a value to a text box. The calculation is done in a for loop. In the loop is a conditional that is a global variable, a boolean. If the boolean is true, break ends the loop (or is supposed to!). A STOP button has an onclick function that sets the global variable to true.
What happens, though, is that the function for the STOP button is not executed until the for loop reaches the maximum value set for i. Anyone know how you can get one button to stop a process started by another?
I had a need for a two dimentional array. Looking for this solution, I ran accross a statement than all Javascipt arrays were arrays of objects. So I created a function prototype, at least thats what I was calling it:
Next I did: var myobject=new objRow("1", "1234 Main St.", "Apt 101");
At this point I was able to see myobject.addr1 or any other variable in the object instance.
Now I added this object to a table. var aryTestTable= new Array(); aryTestTable[0]= myobject; At this point I could see aryTestTable[0].addr1 Next I tried an additional object myobject=new objRow("1", "1234 Main St.", "Apt 101"); //with different data And added it to the table aryTestTable[1]= myobject; Where I could see: aryTestTable[1].addr2 or any other variable.
so far so good. Then I started the actual application code where I was reading a database table and creating the objects and adding them to the table. This was in a for loop wherein the myobject=new objRow("1", "1234 Main St.", "Apt 101"); was instantiated.
After the for loop was finished, I could not access the data in the table - undefined.
So my questions are: Have the my object instances popped off the stack? and What is the alternative way to implement this table of rows of values.
I'm showing a form in a Simplemodal dialog in combination with ajaxForm() to redirect the resulting page to another DOM element. The success function of ajaxForm() closes the modal dialog.The resulting page in the other DOM element has no access to the jquery function $(). When I load a page using ajax into the DOM element there is no issue access the jquery function, this only happens when I redirect the resulting page from the ajaxForm() function.
I've just realized that in Mozilla pointer variables always have local scope in a function. Unlike IE. I wondered if Mozilla was able to do it in some other way? readXML() is an init() function which might be a constraint - I'm no javascript expert.
// The following won't work in Mozilla.
var record;
function readXML() { record=xmlDoc.getElementsByTagName("record"); }
LiveSearch.prototype.initialize = function() { $("#thebutton").mousedown(function() { //when we click the button alert(this.theglobal); }); }
$(document).ready(function() { var objSearch = new LiveSearch("globalvalue"); }); </script>
On page load I create a new LiveSearch instance and it assigns theGlobal = "globalvalue" and proceeds to initialize(); At this point Im using JQuery to setup an onmousedown event on a button on my page with id="thebutton". When I click the button the alert comes back with 'undefined'. How can I get direct access to my theglobal variable? Code:
I've discovered a scenario where Safari 1.3 (I need to make my stuff compliant with 1.3+) gets confused about the scope of local variables WITHIN functions that were created in dynamic script blocks. I've made this example where function def has a local i variable in a loop, and it calls function abc which also has a local i variable in a loop. What happens is that Safari is not respecting the scope and is allowing the called function to corrupt a local variable in the parent function
Here's the whole test page including html tags. If you try it you'll see that IE and Gecko both produce the output "in abc" twice, because the def function correctly gets to call abc twice. On Safari, i gets corrupted, and abc only gets called once... Any ideas what I can do to prevent this? Code: