Closures are functions whose lexical representation includes variables that aren’t evaluated, meaning that functions are capable of using variables defined outside of the function itself. Using global variables in ECMAScript is a simple example of a closure. Consider the following example:
var sMessage = “Hello World!”;
function sayHelloWorld() {
alert(sMessage);
}
sayHelloWorld();
var iBaseNum = 8; Note:被称为Closure的function必须在其外层function的作用域范围内,即必须将其函数定义写在其外层函数的大括号内({})。
In this code, the variable sMessage isn’t evaluated for the function sayHelloWorld() while the scripts is being loaded into memory. The function captures sMessage for later use, which is to say that the interpreter knows to check the value of sMessage when the function is called. When sayHelloWorld() is called (on the last line), the value of sMessage is assigned and the message “Hello World!” is displayed.
Closures can get more complicated, as when you are defining a function inside of another function, as shown here:
function addNumbers(iNum1, iNum2) {
function doAddition() {
return iNum1 + iNum2 + iBaseNum;
}
return doAddition();
}
Here, the function addNumbers() contains a function (the closure) named doAddition(). The internal function is a closure because it captures the arguments of the outer function, iNum1 and iNum2, as well as the global variable iBaseNum. The last step of addNumbers() calls the inner function, which adds the two arguments and the global variable and returns the value. The important concept to grasp here is that doAddition() doesn’t accept any arguments at all; the values it uses are captured from the execution environment.
As you can see, closures are a very powerful, versatile part of ECMAScript that can be used to perform complex calculations. Just as when you use any advanced functionality, exercise caution when using closures because they can get extremely complex.
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛