I am preparing for a job interview as a JS developer and I bumped into this closure definition:     A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in the parent function scope.   Let's consider two different pieces of code:  function a() {     const temp = 1;      function b() {          console.log(temp);      }         }     So obviously function b is a closure, because it was declared inside function a and has access to its variable temp.  But what if I declare just a function just like that, without an IIFE:  function c() {     alert("Hi") // a function taken from the global scope }   My c function wasn't declared inside any function, yet it has access to the global scope. Can it be called a closure, or should it be specifically declared inside another function to be called one?
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.
46209
Using instance methods as callbacks for event handlers changes the scope of this from "My instance" to "Whatever just called the callback". So my code looks like this  function MyObject() {   this.doSomething = function() {     ...   }    var self = this   $('#foobar').bind('click', function(){     self.doSomethng()     // this.doSomething() would not work here   }) }   It works, but is that the best way to do it? It looks strange to me.
41914
Consider:  int testfunc1 (const int a) {   return a; }  int testfunc2 (int const a) {   return a; }   Are these two functions the same in every aspect or is there a difference?  I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well.
124175
Is it possible to do something like this  #ifdef SOMETHING #define foo // #else #define foo MyFunction #endif   The idea is that if SOMETHING is defined, then calls to foo(...) become comments (or something that doesn't get evaluated or compiled), otherwise it becomes a call to MyFunction.  I've seen __noop used, but I don't believe I can use that.  EDIT(s):  I don't think I can really use a macro here, because MyFunction takes a variable number of arguments.  Also, I'd like to make it so the arguments are NOT evaluated!  (So doing something like commenting out the body of MyFunction doesn't really give me what I need, as the arguments will still be evaluated)
647
I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.  The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.  The two ways are:  var functionOne = function() {     // Some code };     function functionTwo() {     // Some code }   What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?
42411
How to check whether a JavaScript variable defined in cross-browser way?  I ran into this problem when writing some JavaScript utilizing FireBug logging. I wrote some code like below:  function profileRun(f) {     // f: functions to be profiled     console.profile(f.constructor);     f();     console.profileEnd(f.constructor); }   It works fine in FireFox/FireBug, but it reports error in IE8 RC1. So, I'd like to do some checking whether console variable exists in the execution environment.  Below code works fine in FireFox, but not in IE8 RC1.   function profileRun(f) {     if (console != undefined) {         console.profile(f.constructor);     }      f();      if (console != undefined) {         console.profileEnd(f.constructor);     } }   However, if I do it this way. It works in IE8 RC1. Why?   function profileRun(f) {     if (window.console != undefined) {         console.profile(f.constructor);     }      f();      if (window.console != undefined) {         console.profileEnd(f.constructor);     } }   Is there any cross-browser way to check it?
36147
The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:  void methodName() {   int i = 7;   for (int j = 0; j &lt; 10; j++) {     int i = j * 2;   } }   Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school.  Perl can do this, as can Scheme, and even C.  Even PL/SQL supports this!  What's the rationale for this design decision for Java?  Edit: as somebody pointed out, Java does have block-scoping.  What's the name for the concept I'm asking about?  I wish I could remember more from those language-design classes. :)
102637
I am reading the book 'Practical Common Lisp' by Peter Seibel. In Chapter 6, &quot;Variables&quot; sections &quot;Lexical Variables and Closures&quot; and &quot;Dynamic, a.k.a. Special, Variables&quot;.  My problem is that the examples in both sections show how (let ...) can shadow global variables and doesn't really tell the difference between the Dynamic and Lexical vars. I understand how closures work but I don't really get whats so special about let in this example: (defvar *x* 10)  (defun foo ()   (format t &quot;Before assignment~18tX: ~d~%&quot; *x*)   (setf *x* (+ 1 *x*))   (format t &quot;After assignment~18tX: ~d~%&quot; *x*))   (defun bar ()   (foo)   (let ((*x* 20)) (foo))   (foo))   CL-USER&gt; (foo) Before assignment X: 10 After assignment  X: 11 NIL   CL-USER&gt; (bar) Before assignment X: 11 After assignment  X: 12 Before assignment X: 20 After assignment  X: 21 Before assignment X: 12 After assignment  X: 13 NIL  I feel like there is nothing special is going on here. The outer foo in bar increments the global x, and foo surrounded by let in bar increments the shadowed x. What's the big deal? I don't see how is this supposed to explain the difference between lexical and dynamic variables. Yet the book continues like this:  So how does this work? How does LET know that when it binds x it's supposed to create a dynamic binding rather than a normal lexical binding? It knows because the name has been declared special.12 The name of every variable defined with DEFVAR and DEFPARAMETER is automatically declared globally special.  What would happen if let would bind x using &quot;normal lexical binding&quot;? All in all, what are the differences between dynamic and lexical binding and how is this example special regarding dynamic binding?
13003
I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.  function foo(id) {     this.dom = document.getElementById(id);     this.bar = 5;     var self = this;     this.dom.addEventListener("click", self.onclick, false); }  foo.prototype = {     onclick : function() {         this.bar = 7;     } };   Now when I create a new object (after the DOM has loaded, with a span#test)  var x = new foo('test');   The 'this' inside the onclick function points to the span#test and not the foo object.  How do I get a reference to my foo object inside the onclick function?
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?"; }
71695
This code always works, even in different browsers:  function fooCheck() {   alert(internalFoo()); // We are using internalFoo() here...    return internalFoo(); // And here, even though it has not been defined...    function internalFoo() { return true; } //...until here! }  fooCheck();   I could not find a single reference to why it should work, though. I first saw this in John Resig's presentation note, but it was only mentioned. There's no explanation there or anywhere for that matter.  Could someone please enlighten me?
42128
I was surprised to find the clamp function absent from  and . Is this mainly a concept particular to computer programming? Is it known by another name in mathematics? I'll be editing the Wikipedia shortly to include a reference to this function but I want to make sure I'm not omitting some synonymous terms I'm currently unaware of.  $$   \operatorname{clamp}(x) = \max( a , \min( x , b ) ) \in [a,b] $$
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.
102600
Finding the closure of A=$\mathbb Q \cap [0,1]$.  My attempt: Between every two rational numbers, there is a rational number. That means that for  any arbitrarily small $\epsilon \gt0$, and some $q\in \mathbb Q \cap [0,1]$  there is $x \notin \mathbb Q$, $x\in [0,1]$ so that $x\in (q-\epsilon, q+\epsilon)$. That means - and I'm not sure if that's correct and how to show it - there is a sequence $\{a_n\}_{n=1}^\infty \subseteq \mathbb Q \cap [0,1]$ so that $\lim_{n \rightarrow \infty} a_n=x$.   Therefore, the closure of A is $[0,1]$.   Is this correct? And how do I show my missing step (if it's valid?).  Thanks for any assistance in advance!
51439
How do you do "inline functions" in C#? I don't think I understand the concept. Are they like anonymous methods? Like lambda functions?  Note: The answers almost entirely deal with the ability to , i.e. "a manual or compiler optimization that replaces a function call site with the body of the callee." If you are interested in , see  or .
8344
I'm working with a bit of html and Javascript code that I've taken over from someone else. The page reloads a table of data (via an asynchronous request) every ten seconds, and then re-builds the table using some DOM code. The code in question looks something like this:  var blah = xmlres.getElementsByTagName('blah'); for(var i = 0; i &lt; blah.length; i++) {     var td = document.createElement('td');     var select = document.createElement('select');     select.setAttribute("...", "...");     select.onchange = function() {         onStatusChanged(select, callid, anotherid);     };     td.appendChild(select); }   When the onchange event is fired for a &lt;select&gt; element however, it seems like the same values are being passed to the onStatusChanged() method for every &lt;select&gt; in the table (I've verified that in each iteration of the loop, callid and anotherid are being given new, distinct values).   I suspect this is occuring because of the nature of how I am setting the event handler, with the select.onchange = function() syntax. If I understand how this is working correctly, this syntax sets a closure for the onchange event to be a function which refers to these two references, which end up having a final value of whatever they are set to on the last iteration of the loop. When the event fires, the value referenced by callid and anotherid is the value set in the last iteration, not the value set at the individual iteration.  Is there a way that I can copy the value of the parameters I am passing to onStatusChanged()?  I've changed the title to better reflect the question and the accepted answer.
23614
This question has bugged me for a while. I want to write a nested function, f(g(x)). If I naively enter it:  \begin{align}     f(g(x))=y \end{align}     The problem is that each and every parenthesis is the same size as all of the others. Shouldn't the outer parentheses be larger? But if I do this:  \begin{align}     f\left(g(x)\right)=y \end{align}     Now it looks even less like the functions are nested. What's the proper way to do this?