Content deleted Content added
→Differences in semantics: fix syntaxhighlight errors |
|||
Line 174:
As different languages do not always have a common definition of the lexical environment, their definitions of closure may vary also. The commonly held minimalist definition of the lexical environment defines it as a set of all [[Name binding|bindings of variables]] in the scope, and that is also what closures in any language have to capture. However the meaning of a [[Variable (programming)|variable]] binding also differs. In imperative languages, variables bind to relative locations in memory that can store values. Although the relative ___location of a binding does not change at runtime, the value in the bound ___location can. In such languages, since closure captures the binding, any operation on the variable, whether done from the closure or not, are performed on the same relative memory ___location. This is often called capturing the variable "by reference". Here is an example illustrating the concept in [[ECMAScript]], which is one such language:
<syntaxhighlight lang="
// Javascript
var f, g;
Line 197:
===Example 1: Reference to an unbound variable===
<ref>{{cite web |title=Function.prototype.bind() |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind |website=MDN Web Docs |access-date=20 November 2018}}</ref>
<syntaxhighlight lang="
var module = {
x: 42,
Line 213:
For this example the expected behaviour would be that each link should emit its id when clicked; but because the variable 'e' is bound the scope above, and lazy evaluated on click, what actually happens is that each on click event emits the id of the last element in 'elements' bound at the end of the for loop.<ref>{{cite web |title=Closures |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Creating_closures_in_loops_A_common_mistake |website=MDN Web Docs |access-date=20 November 2018}}</ref>
<syntaxhighlight lang="
var elements= document.getElementsByTagName('a');
//Incorrect: e is bound to the function containing the 'for' loop, not the closure of "handle"
|