ECMAScript Closure
- Previous Page Function Object
- Next Page Object-Oriented
One of the most misunderstood points about ECMAScript is that it supports closures (closures).
Closures refer to functions that include lexical scope including variables that are not calculated, that is, functions can use variables defined outside the function.
Simple Closure Example
Using global variables in ECMAScript is a simple closure example. Consider the following code:
var sMessage = "hello world"; function sayHelloWorld() { alert(sMessage); } sayHelloWorld();
In the above code, after the script is loaded into memory, the value of the variable sMessage is not calculated for the function sayHelloWorld(). The function captures the value of sMessage only for future use, that is, the interpreter knows that it needs to check the value of sMessage when calling the function. sMessage will be assigned a value when the function sayHelloWorld() is called (on the last line) and displays the message "hello world".
Complex Closure Example
Defining one function within another makes closures more complex. For example:
var iBaseNum = 10; function addNum(iNum1, iNum2) { function doAdd() { return iNum1 + iNum2 + iBaseNum; } return doAdd(); }
Here, the function addNum() includes the function doAdd() (closure). The inner function is a closure because it captures the values of the external function's parameters iNum1 and iNum2, as well as the value of the global variable iBaseNum. The final step of addNum() calls doAdd(), adds the two parameters and the global variable, and returns their sum.
The important concept to grasp here is that the doAdd() function does not accept any parameters; it uses values obtained from the execution environment.
As can be seen, closures are a very powerful and versatile part of ECMAScript, which can be used to perform complex calculations.
Tip:As with any advanced function, be careful when using closures because they can become very complex.
- Previous Page Function Object
- Next Page Object-Oriented