分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.youkuaiyun.com/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
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();
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:
var iBaseNum = 8;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.
注:被称为Closure的function必须在其外层function的作用域范围内,即必须将其函数定义写在其外层函数的大括号内({})。
给我老师的人工智能教程打call!http://blog.youkuaiyun.com/jiangjunshow
