I try to learn javascript and therefore I tried the following code:  function repeat(n, action) {     for (var i = 0; i &lt; n; i++) {         action();     } } function benchmark() {     var start = [], end = [], timings = [];     repeat(1000, function() {         start.push(Date.now());         // Repeat something         end.push(Date.now());     });      for (var i = 0; i &lt; end.length; i++) {         timings[i] = end[i] - start[i];     }      return timings; }   My Question now: Why can I access start and end in my callback? As I understood the scope changed from benchmark to repeat. Is the callback a closure or is a closure onle a defined named function in another function?  Thanks!
1086
How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?  I have seen  given on Wikipedia, but unfortunately it did not help.
23702
Just curious:    4 instanceof Number => false new Number(4) instanceof Number => true?   Why is this? Same with strings:    'some string' instanceof String returns false new String('some string') instanceof String => true String('some string') instanceof String also returns false ('some string').toString instanceof String also returns false   For object, array or function types the instanceof operator works as expected. I just don't know how to understand this.  [new insights]  Object.prototype.is = function() {         var test = arguments.length ? [].slice.call(arguments) : null            ,self = this.constructor;         return test ? !!(test.filter(function(a){return a === self}).length)                : (this.constructor.name ||                   (String(self).match ( /^function\s*([^\s(]+)/im )                     || [0,'ANONYMOUS_CONSTRUCTOR']) [1] ); } // usage var Newclass = function(){};  // anonymous Constructor function var Some = function Some(){}; // named Constructor function (5).is();                     //=&gt; Number 'hello world'.is();           //=&gt; String (new Newclass()).is();        //=&gt; ANONYMOUS_CONSTRUCTOR (new Some()).is();            //=&gt; Some /[a-z]/.is();                 //=&gt; RegExp '5'.is(Number);               //=&gt; false '5'.is(String);               //=&gt; true
4188
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:  flist = []  for i in xrange(3):     def func(x): return x * i     flist.append(func)  for f in flist:     print f(2)   Note that this example mindfully avoids lambda. It prints "4 4 4", which is surprising. I'd expect "0 2 4".   This equivalent Perl code does it right:  my @flist = ();  foreach my $i (0 .. 2) {     push(@flist, sub {$i * $_[0]}); }  foreach my $f (@flist) {     print $f-&gt;(2), "\n"; }   "0 2 4" is printed.  Can you please explain the difference ?    Update:   The problem is not with i being global. This displays the same behavior:  flist = []  def outer():     for i in xrange(3):         def inner(x): return x * i         flist.append(inner)  outer() #~ print i   # commented because it causes an error  for f in flist:     print f(2)   As the commented line shows, i is unknown at that point. Still, it prints "4 4 4".
1085
Does the "for…in" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn't do it in order? The object I wish to use will be declared once and will never be modified.  Suppose I have:  var myObject = { A: "Hello", B: "World" };   And I further use them in:  for (var item in myObject) alert(item + " : " + myObject[item]);   Can I expect 'A : "Hello"' to always come before 'B : "World"' in most decent browsers?
27582
I have a set of global counter variables in Javascript:  var counter_0 = 0; var counter_1 = 0; var counter_2 = 0;   etc  I then have a Javascript function that accepts an 'index' number that maps to those global counters. Inside this function, I need to read and write to those global counters using the 'index' value passed to the function.  Example of how I'd like it to work, but of course doesn't work at all:  function process(index) {     // do some processing      // if 'index' == 0, then this would be incrementing the counter_0 global variable     ++counter_+index;       if (counter_+index == 13)     {         // do other stuff     } }   I hope what I'm trying to accomplish is clear. If not I'll try to clarify. Thanks.  EDIT Clarification:  I'm not trying to increment the name of the counter, but rather the value the counter contains.
46765
Take the below code:  private void anEvent(object sender, EventArgs e) {     //some code }     What is the difference between the following ?  [object].[event] += anEvent;  //and  [object].[event] += new EventHandler(anEvent);   [UPDATE]  Apparently, there is no difference between the two...the former is just syntactic sugar of the latter.
7437
I have a method that uses the  function and makes a call to another method. On initial load method 2 works fine. However, after the timeout, I get an error that says method2 is undefined. What am I doing wrong here?  ex:  test.prototype.method = function() {     //method2 returns image based on the id passed     this.method2('useSomeElement').src = "http://www.some.url";     timeDelay = window.setTimeout(this.method, 5000); };  test.prototype.method2 = function(name) {     for (var i = 0; i &lt; document.images.length; i++) {         if (document.images[i].id.indexOf(name) &gt; 1) {             return document.images[i];         }     } };
122
What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?
110522
Possible Duplicate:          I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)  Is it good for anything else? Do you use it?
26511
I’m looking for a trick about this. I know how to call a dynamic, arbitrary function in JavaScript, passing specific parameters, something like this:  function mainfunc(func, par1, par2){     window[func](par1, par2); }  function calledfunc(par1, par2){     // Do stuff here }  mainfunc('calledfunc', 'hello', 'bye');   I know how to pass optional, unlimited parameters using the arguments collection inside mainfunc, but, I can’t figure how to send an arbitrary number of parameters to mainfunc to be sent to calledfunc dynamically; how can I accomplish something like this, but with any number of optional arguments (not using that ugly if–else)?  function mainfunc(func){     if(arguments.length == 3)         window[func](arguments[1], arguments[2]);     else if(arguments.length == 4)         window[func](arguments[1], arguments[2], arguments[3]);     else if(arguments.length == 5)         window[func](arguments[1], arguments[2], arguments[3], arguments[4]); }  function calledfunc1(par1, par2){     // Do stuff here }  function calledfunc2(par1, par2, par3){     // Do stuff here }  mainfunc('calledfunc1', 'hello', 'bye'); mainfunc('calledfunc2', 'hello', 'bye', 'goodbye');
74496
Please advise how to pass parameters into a function called using setInterval.  My example setInterval(funca(10,3), 500); is incorrect.
87503
I always read that it is recommended to set objects to nothing, once I am done with them. But I normally use them only in functions inside forms.  Isn't the reference lost and memory released when the function scope is left, regardless of setting objects to Nothing?   i.e. is it really necessary to do:  Set db = Nothing Set record_set = Nothing
19901
...where each object also has references to other objects within the same array?  When I first came up with this problem I just though of something like   var clonedNodesArray = nodesArray.clone()   would exist and searched for info on how to clone objects in javascript. I did find a  on StackOverflow (answered by the very same @JohnResig) and he pointed out that with jQuery you could do  var clonedNodesArray = jQuery.extend({}, nodesArray);   to clone an object. I tried this though, this only copies the references of the objects in the array. So if I   nodesArray[0].value = "red" clonedNodesArray[0].value = "green"   the value of both nodesArray[0] and clonedNodesArray[0] will turn out to be "green". Then I tried  var clonedNodesArray = jQuery.extend(true, {}, nodesArray);   which deep copies an Object, but I got "too much recursion" and "control stack overflow" messages from both Firebug and Opera Dragonfly respectively.  How would you do it? Is this something that shouldn't even be done? Is there a reusable way of doing this in Javascript?
78588
How do you tell if a function in JavaScript is defined?  I want to do something like this  function something_cool(text, callback) {     alert(text);     if( callback != null ) callback(); }   But it gets me a     callback is not a function   error when callback is not defined.
104870
I've been working on this task (see screenshot).     Here's my answer to it so far:  var sum_pairs=function(ints, s){   //your code here    var ptr_1 = 0,       ptr_2 = 0,       i = 0,       j = 0,       len = ints.length,       j_min = len,       arr_sum = [];    for (i; i &lt; len-1; i++){     for (j = i+1; j &lt; len; j++){       if(ints[i] + ints[j] === s){         if (j &lt; j_min){           j_min = j;           arr_sum = [parseInt(ints[i]), parseInt(ints[j])]         }       }     }   }  return ( (arr_sum.length === 0)? undefined : arr_sum );   }   However, while the tests all pass, it throws an STDERR about 'optimising the code':    How might I be able to optimise my code further?
24968
If a variable is declared as static in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?  void foo()  {      static string plonk = "When will I die?"; }
85912
I am using PHP and JavaScript. My JavaScript code contains a function, get_data():  function get_Data(){     var name;     var job;     .....      return buffer; }   Now I have PHP code with the following.  &lt;?php     $i=0;     $buffer_data;      /* Here I need to get the value from JavaScript get_data() of buffer;        and assign to variable $buffer_data. */ ?&gt;   How do I assign the JavaScript function data into the PHP variable?