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的作用域范圍內(nèi),即必須將其函數(shù)定義寫在其外層函數(shù)的大括號(hào)內(nèi)({})。
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.
如對(duì)本文有疑問,請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答??! 點(diǎn)擊進(jìn)入論壇